In Kubernetes, you can use labels to assign key-value pairs to any resources.
Labels are ubiquitous and necessary to everyday operations such as creating services.
However, how should you name and use those labels?
Any resource in Kubernetes can have labels.
Some labels are vital (e.g. service's selector, operators, etc.), and others are useful to tag resources (e.g. labelling a deployment).
Kubectl offers a
--show-labels flag to help you list resources and their labels.
If you list pods, deployments and services in an empty cluster, you might notice that Kubernetes uses the
component=<name> label to tag pods.
Kubernetes recommends six labels for your resources:
- Part of
- Managed By
Let's look at an excellent example of using those labels: the Prometheus Helm chart.
The charts install five pods (i.e. server, alter manager, node exporter, push gateway and kube state metrics).
Notice how not all labels are applied to all pods.
Labelling resources properly helps you make sense of what's deployed.
For example, you can filter results with kubectl:
kubectl get pods -l "environment in (staging, dev)"
The command above only lists pod in staging and dev.
If those labels are not what you are after, you can always create your own.
<prefix>/<name> key is recommended — e.g.
The following labels could be used in a multitenant cluster:
- Business unit
- Development team
- Shared services
- Asset classification
Alongside labels, you have annotations.
Whereas labels are used to select resources, annotations decorate resources with metadata.
You cannot select resources with annotations.
Administrators can assign annotations to any workload.
However, more often, Kubernetes and operators decorate resources with extra annotations.
A good example is the annotation
kubernetes.io/ingress-bandwidth to assign bandwidth to pods.
The official documentation has a list of well-known labels and annotations.
Here are some examples:
Annotations are used extensively in operators.
Look at all the annotations you can use with the ingress-nginx controller.
Unfortunately, using operators/cloud providers/etc. annotations is not always a good idea if you wish to stay vendor-neutral.
However, sometimes it's also the only option (e.g. having an AWS ALB deployed in the correct subnet when using a service of type LoadBalancer).
Here are a few links if you want to learn more:
- The Guide to Kubernetes Labels
- Well-Known Labels, Annotations and Taints
- Recommended Labels
- Label standard and best practices for Kubernetes security
And finally, if you've enjoyed this thread, you might also like:
Top comments (0)