A label is a key-value tag used to select objects; an annotation is a note used to document them. You already know them, without having seen all their syntax: the lessons on Pods, ReplicaSets and Deployments defined labels, the selector of a ReplicaSet finds its Pods through them, and the lesson Deployments set the kubernetes.io/change-cause annotation, whose trap Rolling updates and rollbacks shows. This lesson teaches you to handle them with kubectl label and kubectl annotate, then to filter with -l. It prepares the lesson on Services: a Service finds its Pods in exactly this way.
Prerequisites: the lessons Pods, Deployments and ReplicaSets, and the demo cluster from First cluster.
What you will learn
- Tell a label from an annotation, and choose the right one of the two
- Add, change and remove a label or an annotation with
kubectl labelandkubectl annotate - Filter resources with a label selector (
-l) - Explain why a label set by hand on a Pod disappears with it
- Recognize the recommended
app.kubernetes.io/*labels
Label or annotation: what is the difference?
A single question settles it: will Kubernetes or a tool have to select objects with this information? If so, it is a label, short and constrained, which selectors know how to read. If not, it is an annotation, free text that nobody filters on but that everybody can read. Both live in the metadata block of the object.
| Criterion | Label | Annotation |
|---|---|---|
| Role | Identify, group, select | Document, configure a tool |
Read by a selector (-l, Service, ReplicaSet) | Yes | No |
| Size of the value | 63 characters at most | 256 KiB for all the annotations of an object |
| Characters of the value | Letters, digits, -, _, . | Free text |
| Example | app=web, env=production | a contact, a runbook URL |
Information that is long, changing or meant for humans (contact address, link, reason for a change) is therefore an annotation. A sorting criterion (application, environment, role) is a label.
Set, change and remove a label
The command kubectl label <type> <name> <key>=<value> writes a label on any object: Pod, Deployment, node. First create two Deployments, web (3 replicas) and api (2 replicas). kubectl create deployment writes the app label in the template of their Pods, and the Deployment controller adds pod-template-hash to it.
kubectl config use-context kind-demokubectl create deployment web --replicas=3 \ --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbkubectl create deployment api --replicas=2 \ --image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbkubectl rollout status deployment/web --timeout=90skubectl rollout status deployment/api --timeout=90skubectl get pods --show-labelsSwitched to context "kind-demo".deployment.apps/web createddeployment.apps/api createdWaiting for deployment "web" rollout to finish: 0 of 3 updated replicas are available...[...]deployment "web" successfully rolled outWaiting for deployment "api" rollout to finish: 1 of 2 updated replicas are available...deployment "api" successfully rolled outNAME READY STATUS RESTARTS AGE LABELSapi-698865cd4b-plfwg 1/1 Running 0 17s app=api,pod-template-hash=698865cd4b,topology.kubernetes.io/zone=zone-capi-698865cd4b-vwm6m 1/1 Running 0 17s app=api,pod-template-hash=698865cd4b,topology.kubernetes.io/zone=zone-bweb-5f9ccb876d-clnwv 1/1 Running 0 17s app=web,pod-template-hash=5f9ccb876d,topology.kubernetes.io/zone=zone-aweb-5f9ccb876d-jprz2 1/1 Running 0 17s app=web,pod-template-hash=5f9ccb876d,topology.kubernetes.io/zone=zone-bweb-5f9ccb876d-lsjpj 1/1 Running 0 17s app=web,pod-template-hash=5f9ccb876d,topology.kubernetes.io/zone=zone-cThe topology.kubernetes.io/zone label comes from neither of the two Deployment templates: the API server copies it from the node that the scheduler chose, at the moment it binds the Pod to that node. An admission plugin is a check that the API server applies to the objects it receives; this one is called PodTopologyLabels, it has been enabled by default since Kubernetes 1.35 and also copies topology.kubernetes.io/region when the node carries it.
The following commands target a specific Pod. Store the name of the first web Pod in a shell variable, and reuse it in the same terminal (run this line again if you open a new terminal):
POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')echo "$POD"web-5f9ccb876d-clnwvAdd a label
Without any option, the command adds the key if it is absent and answers with one line that names the resource it touched.
kubectl label pod "$POD" env=productionpod/web-5f9ccb876d-clnwv labeledChange an existing label: --overwrite
Running the command again with another value fails: kubectl refuses to overwrite a label by accident, and the message gives the value in place. The error below is intended.
kubectl label pod "$POD" env=stagingkubectl label pod "$POD" env=staging --overwriteerror: 'env' already has a value (production), and --overwrite is falsepod/web-5f9ccb876d-clnwv labeledThe --overwrite option lifts this safeguard. This is intended: replacing a value can take the object out of a selector, and therefore change what the cluster does.
Remove a label: the trailing dash
A dash stuck behind the key removes the label. It is not a typo, it is the removal syntax, the same as for an annotation. Removing an absent key is not an error.
kubectl label pod "$POD" env-kubectl label pod "$POD" env-pod/web-5f9ccb876d-clnwv unlabeledlabel "env" not found.pod/web-5f9ccb876d-clnwv not labeledLabel several resources at once
The command accepts several names, --all for every object of the type in the current namespace (see Namespaces), or a -l selector. Before a bulk change, --dry-run=server has the API validate the request and lists the targeted objects without modifying anything.
kubectl label pods -l app=web tier=frontend --dry-run=serverkubectl label pods -l app=web tier=frontendkubectl label pods -l app=api tier=backendpod/web-5f9ccb876d-clnwv labeled (server dry run)pod/web-5f9ccb876d-jprz2 labeled (server dry run)pod/web-5f9ccb876d-lsjpj labeled (server dry run)pod/web-5f9ccb876d-clnwv labeledpod/web-5f9ccb876d-jprz2 labeledpod/web-5f9ccb876d-lsjpj labeledpod/api-698865cd4b-plfwg labeledpod/api-698865cd4b-vwm6m labeledFilter with a label selector (-l)
The -l option filters kubectl get, delete or logs on the labels of the objects. This is what a Service does: it does not know its Pods by name, it finds them with an equality selector such as app=web, just like the ReplicaSet. To compare the forms of selector, set an environment on two web Pods:
POD1=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')POD2=$(kubectl get pods -l app=web -o jsonpath='{.items[1].metadata.name}')kubectl label pod "$POD1" env=productionkubectl label pod "$POD2" env=stagingkubectl get pods -l app=web,env=productionpod/web-5f9ccb876d-clnwv labeledpod/web-5f9ccb876d-jprz2 labeledNAME READY STATUS RESTARTS AGEweb-5f9ccb876d-clnwv 1/1 Running 0 17sThe comma reads as "and": all the conditions must be true. The table gives the other forms; put in single quotes those that contain parentheses, spaces or a !, so that the shell does not interpret them.
| Selector | Keeps the objects… | Expected result here |
|---|---|---|
-l env=production | whose env equals production | 1 Pod |
-l env!=staging | whose env does not equal staging, including those without env | 4 Pods |
-l 'env in (production, staging)' | whose env equals one of the values | 2 Pods |
-l 'env notin (staging)' | whose env equals none of these values, including those without env | 4 Pods |
-l env | that carry the env key, whatever its value | 2 Pods |
-l '!env' | that do not carry the env key | 3 Pods |
Count the Pods kept by each form:
for s in 'env=production' 'env!=staging' 'env in (production, staging)' 'env notin (staging)' 'env' '!env'; do echo "$s : $(kubectl get pods -l "$s" --no-headers | wc -l)"doneenv=production : 1env!=staging : 4env in (production, staging) : 2env notin (staging) : 4env : 2!env : 3The trap is in the second line: != also keeps the objects that do not have the key. The two api Pods come out although they have no env label. To target only the objects that carry the key, combine: -l env,env!=staging. The selector also serves for bulk changes: a single command sets env=dev on all the Pods that do not have an environment yet.
kubectl label pods -l '!env' env=devkubectl get pods -L envpod/api-698865cd4b-plfwg labeledpod/api-698865cd4b-vwm6m labeledpod/web-5f9ccb876d-lsjpj labeledNAME READY STATUS RESTARTS AGE ENVapi-698865cd4b-plfwg 1/1 Running 0 18s devapi-698865cd4b-vwm6m 1/1 Running 0 18s devweb-5f9ccb876d-clnwv 1/1 Running 0 18s productionweb-5f9ccb876d-jprz2 1/1 Running 0 18s stagingweb-5f9ccb876d-lsjpj 1/1 Running 0 18s devThe -L env option turns a label into a column; --show-labels displays them all. Several keys are separated by a comma (-L app,env,tier), and an empty cell signals an object that does not carry the key.
Why does a label set by hand not last?
A label set with kubectl label lives on a specific object and disappears with it. Set a diagnostic label on a web Pod, then delete that Pod:
kubectl label pod "$POD1" debug=ouikubectl get pods -l debug=ouikubectl delete pod "$POD1"kubectl rollout status deployment/web --timeout=90skubectl get pods -l app=web -L debugpod/web-5f9ccb876d-clnwv labeledNAME READY STATUS RESTARTS AGEweb-5f9ccb876d-clnwv 1/1 Running 0 18spod "web-5f9ccb876d-clnwv" deleted from default namespacedeployment "web" successfully rolled outNAME READY STATUS RESTARTS AGE DEBUGweb-5f9ccb876d-288zb 1/1 Running 0 2sweb-5f9ccb876d-jprz2 1/1 Running 0 20sweb-5f9ccb876d-lsjpj 1/1 Running 0 20sThe Deployment recreated a Pod to get back to three, from its Pod template: the new one does not have the debug label. A lasting label is therefore written in the Pod template (spec.template.metadata.labels). Write it there, and all the Pods carry it. The kubectl patch command modifies a field of an existing object from a JSON fragment, without going through a file:
kubectl patch deployment web -p '{"spec":{"template":{"metadata":{"labels":{"debug":"oui"}}}}}'kubectl rollout status deployment/web --timeout=90skubectl get pods -l debug=ouideployment.apps/web patchedWaiting for deployment spec update to be observed...Waiting for deployment "web" rollout to finish: 0 out of 3 new replicas have been updated...[...]Waiting for deployment "web" rollout to finish: 1 old replicas are pending termination...[...]deployment "web" successfully rolled outNAME READY STATUS RESTARTS AGEweb-56d9f7695d-shcjg 1/1 Running 0 1sweb-56d9f7695d-tkksh 1/1 Running 0 1sweb-56d9f7695d-v8dnh 1/1 Running 0 2sThis change modifies the Pod template, so it triggers a rollout that replaces the Pods, as in the lesson Deployments. To finish, labeling the Deployment itself changes nothing for the Pods:
kubectl label deployment web team=webkubectl get deployments --show-labelskubectl get pods -l team=webdeployment.apps/web labeledNAME READY UP-TO-DATE AVAILABLE AGE LABELSapi 2/2 2 2 22s app=apiweb 3/3 3 3 22s app=web,team=webNo resources found in default namespace.The Pods receive the labels of the Pod template, not those of the Deployment. Remember the rule: kubectl label on a Pod serves to sort or to diagnose, never to configure durably.
What are the syntax rules of a label?
A badly formed label is refused at write time, with a message that quotes the expected pattern. The rules come from the official documentation, Labels and Selectors, and apply to the key as well as to the value.
| Part | Rule |
|---|---|
| Key name | 63 characters at most, letters, digits, -, _, ., starts and ends with a letter or a digit |
| Prefix (optional) | a DNS domain name of 253 characters at most, followed by / (app.kubernetes.io/name) |
| Value | 63 characters at most (empty allowed), same characters, starts and ends with a letter or a digit |
The kubernetes.io/ and k8s.io/ prefixes are reserved for Kubernetes components. The two following commands are refused (intended errors), a value with spaces then a value that is too long:
kubectl label pod "$POD2" "desc=Mon application de production"kubectl label pod "$POD2" description=une-valeur-beaucoup-trop-longue-pour-tenir-dans-un-label-kubernetes-valideerror: invalid label value: "desc=Mon application de production": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345', regex used for validation is '(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?')error: invalid label value: "description=une-valeur-beaucoup-trop-longue-pour-tenir-dans-un-label-kubernetes-valide": must be no more than 63 bytesIf the information does not fit these rules, it belongs in an annotation.
What are the recommended app.kubernetes.io/* labels?
Kubernetes publishes a list of recommended labels, all under the app.kubernetes.io/ prefix. Adopting them gives a common vocabulary to your teams and to the tools that read them, such as Helm or dashboards: env, environment and stage stop coexisting to say the same thing.
| Label | Role | Example |
|---|---|---|
app.kubernetes.io/name | Name of the application | boutique |
app.kubernetes.io/instance | Specific instance of the application | boutique-prod |
app.kubernetes.io/version | Version of the application | 2.4.1 |
app.kubernetes.io/component | Role in the architecture | frontend, database |
app.kubernetes.io/part-of | Overall application | site-marchand |
app.kubernetes.io/managed-by | Tool that manages the object | helm, kubectl |
These labels are written in the manifest, on the Deployment and in its Pod template. Put the version in quotes: without them, YAML reads a value such as 1.10 as a number and kubectl rejects the file.
kubectl apply -f - <<'EOF'apiVersion: apps/v1kind: Deploymentmetadata: name: boutique labels: app.kubernetes.io/name: boutique app.kubernetes.io/version: "2.4.1" app.kubernetes.io/component: frontendspec: replicas: 2 selector: matchLabels: app.kubernetes.io/name: boutique template: metadata: labels: app.kubernetes.io/name: boutique app.kubernetes.io/version: "2.4.1" app.kubernetes.io/component: frontend spec: containers: - name: nginx image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbEOFkubectl rollout status deployment/boutique --timeout=90skubectl get pods -l app.kubernetes.io/name=boutique --show-labelsdeployment.apps/boutique createdWaiting for deployment "boutique" rollout to finish: 0 out of 2 new replicas have been updated...Waiting for deployment "boutique" rollout to finish: 0 of 2 updated replicas are available...Waiting for deployment "boutique" rollout to finish: 1 of 2 updated replicas are available...deployment "boutique" successfully rolled outNAME READY STATUS RESTARTS AGE LABELSboutique-548bc488fb-75fqx 1/1 Running 0 1s app.kubernetes.io/component=frontend,app.kubernetes.io/name=boutique,app.kubernetes.io/version=2.4.1,pod-template-hash=548bc488fb,topology.kubernetes.io/zone=zone-bboutique-548bc488fb-gxgwp 1/1 Running 0 1s app.kubernetes.io/component=frontend,app.kubernetes.io/name=boutique,app.kubernetes.io/version=2.4.1,pod-template-hash=548bc488fb,topology.kubernetes.io/zone=zone-aThe selector includes only the name, not the version: a version that changes at every delivery cannot appear in it without breaking the link between the Deployment and its Pods.
How do you document an object with kubectl annotate?
kubectl annotate is used exactly like kubectl label: same arguments, same --overwrite, same trailing dash to remove. Only the value changes: it is free text, to be put in quotes as soon as it contains spaces. A contact address and a link to an operating procedure (a runbook) are the most common cases.
kubectl annotate deployment web owner="equipe-web@exemple.fr"kubectl annotate deployment web runbook="https://wiki.exemple.fr/runbooks/web" ticket="INC-2026-0142"kubectl annotate deployment web owner="equipe-sre@exemple.fr"kubectl annotate deployment web owner="equipe-sre@exemple.fr" --overwritekubectl annotate deployment web ticket-deployment.apps/web annotateddeployment.apps/web annotatederror: --overwrite is false but found the following declared annotation(s): 'owner' already has a value (equipe-web@exemple.fr)deployment.apps/web annotateddeployment.apps/web annotatedThe third call fails on purpose: changing the owner requires --overwrite, as for a label. kubectl get does not display annotations and has no equivalent of --show-labels. Two paths exist: kubectl describe, which lists them under Annotations:, and jsonpath, which reads a specific field.
kubectl describe deployment web | grep -A4 '^Annotations:'kubectl get deployment web -o jsonpath='{.metadata.annotations.owner}{"\n"}'kubectl get deployments -l ownerAnnotations: deployment.kubernetes.io/revision: 2 owner: equipe-sre@exemple.fr runbook: https://wiki.exemple.fr/runbooks/webSelector: app=webReplicas: 3 desired | 3 updated | 3 total | 3 available | 0 unavailableequipe-sre@exemple.frNo resources found in default namespace.An annotation is not filterable: -l owner returns nothing. This is also why a Service never chooses its Pods by an annotation. The output of describe shows an annotation you did not write, deployment.kubernetes.io/revision: Kubernetes components and many tools store their own information in annotations in this way.
| Annotation | Who sets it | What it is for |
|---|---|---|
deployment.kubernetes.io/revision | the Deployment controller | number of the current revision |
kubectl.kubernetes.io/last-applied-configuration | kubectl apply | copy of the last applied manifest, to compute the next change |
kubernetes.io/change-cause | you | reason displayed by rollout history, see Annotate the changes |
The total size of the annotations of an object, keys and values included, is limited to 256 KiB (262,144 bytes) according to the official annotations documentation. This limit leaves room for documentation, not for encoded files or logs: those belong in a ConfigMap (see ConfigMaps) or in storage outside the cluster.
Clean up the cluster
Delete the three Deployments to start again from a clean cluster: their Pods go to Terminating before disappearing.
kubectl delete deployment web api boutiquekubectl get podsdeployment.apps "web" deleted from default namespacedeployment.apps "api" deleted from default namespacedeployment.apps "boutique" deleted from default namespaceNAME READY STATUS RESTARTS AGEapi-698865cd4b-plfwg 1/1 Terminating 0 24sapi-698865cd4b-vwm6m 1/1 Terminating 0 24sboutique-548bc488fb-75fqx 1/1 Terminating 0 2sboutique-548bc488fb-gxgwp 1/1 Terminating 0 2sweb-56d9f7695d-shcjg 1/1 Terminating 0 3sweb-56d9f7695d-tkksh 1/1 Terminating 0 3sweb-56d9f7695d-v8dnh 1/1 Terminating 0 4sTroubleshooting
Label and annotation errors fall into two families. In the first, kubectl refuses to write and the message says why. In the second, the write succeeds but nothing changes in the cluster, or the label disappears: the cause is almost always an object recreated from a template that does not carry it.
| Symptom | Likely cause | Solution |
|---|---|---|
invalid label value | Value of more than 63 characters, or spaces and forbidden characters | Shorten it, or switch to an annotation |
'env' already has a value (...), and --overwrite is false | The label already exists | Add --overwrite |
--overwrite is false but found the following declared annotation(s) | The annotation already exists | Add --overwrite |
-l returns nothing | Label absent, typo, or objects in another namespace | Check with kubectl get pods --show-labels |
| The label set on a Pod has disappeared | The Pod was recreated from the template of the Deployment | Write the label in spec.template.metadata.labels |
kubectl label deployment does not change the Pods | The Pods take the labels of the template, not of the Deployment | Change the Pod template in the manifest |
Put it into practice
The guided lab starts from two Deployments created by kubectl create deployment in the etiquettes namespace of a kind cluster: web, with three replicas, and api, with two. You add the env=prod label in the Pod template of web, so that it covers all its Pods, present and future, and you set a description annotation on the Deployment. Finally, you record in ~/etiquettes/releve.txt a selector with a negation that returns exactly the Pods of api. The validation refuses a label set by hand on the Pods, a description set as a label and a selector without a negation.
Key takeaways
- A label serves to select (Service, ReplicaSet,
-l); an annotation serves to document and is never filterable. kubectl labelandkubectl annotateshare the syntax:--overwriteto replace, trailing dash (env-) to remove.-l app=web,env=productioncombines conditions with "and";env!=xalso keeps objects without theenvkey.--show-labelsdisplays all the labels,-L envturns one into a column; annotations are read withdescribeor jsonpath.- A label set by hand on a Pod disappears when the Pod is recreated: a lasting label is written in the Pod template of the manifest.
- Label value: 63 characters at most; annotations of an object: 256 KiB in total.
Test your knowledge
Six questions to check the actions of the lesson: set and remove a label, read a selector as a Service will, know where a lasting label must be written, and choose between label and annotation.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Kubernetes Services: expose and connect your applications
A new full quiz with random questions
Work again only on the questions you missed