Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

Kubernetes labels and annotations: kubectl label and annotate

By updated

Improve this page

Logo Kubernetes

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 label and kubectl 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.

CriterionLabelAnnotation
RoleIdentify, group, selectDocument, configure a tool
Read by a selector (-l, Service, ReplicaSet)YesNo
Size of the value63 characters at most256 KiB for all the annotations of an object
Characters of the valueLetters, digits, -, _, .Free text
Exampleapp=web, env=productiona 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.

Terminal window
kubectl config use-context kind-demo
kubectl create deployment web --replicas=3 \
--image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
kubectl create deployment api --replicas=2 \
--image=nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
kubectl rollout status deployment/web --timeout=90s
kubectl rollout status deployment/api --timeout=90s
kubectl get pods --show-labels
Output
Switched to context "kind-demo".
deployment.apps/web created
deployment.apps/api created
Waiting for deployment "web" rollout to finish: 0 of 3 updated replicas are available...
[...]
deployment "web" successfully rolled out
Waiting for deployment "api" rollout to finish: 1 of 2 updated replicas are available...
deployment "api" successfully rolled out
NAME READY STATUS RESTARTS AGE LABELS
api-698865cd4b-plfwg 1/1 Running 0 17s app=api,pod-template-hash=698865cd4b,topology.kubernetes.io/zone=zone-c
api-698865cd4b-vwm6m 1/1 Running 0 17s app=api,pod-template-hash=698865cd4b,topology.kubernetes.io/zone=zone-b
web-5f9ccb876d-clnwv 1/1 Running 0 17s app=web,pod-template-hash=5f9ccb876d,topology.kubernetes.io/zone=zone-a
web-5f9ccb876d-jprz2 1/1 Running 0 17s app=web,pod-template-hash=5f9ccb876d,topology.kubernetes.io/zone=zone-b
web-5f9ccb876d-lsjpj 1/1 Running 0 17s app=web,pod-template-hash=5f9ccb876d,topology.kubernetes.io/zone=zone-c

The 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):

Terminal window
POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
echo "$POD"
Output
web-5f9ccb876d-clnwv

Add 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.

Terminal window
kubectl label pod "$POD" env=production
Output
pod/web-5f9ccb876d-clnwv labeled

Change 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.

Terminal window
kubectl label pod "$POD" env=staging
kubectl label pod "$POD" env=staging --overwrite
Output
error: 'env' already has a value (production), and --overwrite is false
pod/web-5f9ccb876d-clnwv labeled

The --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.

Terminal window
kubectl label pod "$POD" env-
kubectl label pod "$POD" env-
Output
pod/web-5f9ccb876d-clnwv unlabeled
label "env" not found.
pod/web-5f9ccb876d-clnwv not labeled

Label 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.

Terminal window
kubectl label pods -l app=web tier=frontend --dry-run=server
kubectl label pods -l app=web tier=frontend
kubectl label pods -l app=api tier=backend
Output
pod/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 labeled
pod/web-5f9ccb876d-jprz2 labeled
pod/web-5f9ccb876d-lsjpj labeled
pod/api-698865cd4b-plfwg labeled
pod/api-698865cd4b-vwm6m labeled

Filter 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:

Terminal window
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=production
kubectl label pod "$POD2" env=staging
kubectl get pods -l app=web,env=production
Output
pod/web-5f9ccb876d-clnwv labeled
pod/web-5f9ccb876d-jprz2 labeled
NAME READY STATUS RESTARTS AGE
web-5f9ccb876d-clnwv 1/1 Running 0 17s

The 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.

SelectorKeeps the objects…Expected result here
-l env=productionwhose env equals production1 Pod
-l env!=stagingwhose env does not equal staging, including those without env4 Pods
-l 'env in (production, staging)'whose env equals one of the values2 Pods
-l 'env notin (staging)'whose env equals none of these values, including those without env4 Pods
-l envthat carry the env key, whatever its value2 Pods
-l '!env'that do not carry the env key3 Pods

Count the Pods kept by each form:

Terminal window
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)"
done
Output
env=production : 1
env!=staging : 4
env in (production, staging) : 2
env notin (staging) : 4
env : 2
!env : 3

The 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.

Terminal window
kubectl label pods -l '!env' env=dev
kubectl get pods -L env
Output
pod/api-698865cd4b-plfwg labeled
pod/api-698865cd4b-vwm6m labeled
pod/web-5f9ccb876d-lsjpj labeled
NAME READY STATUS RESTARTS AGE ENV
api-698865cd4b-plfwg 1/1 Running 0 18s dev
api-698865cd4b-vwm6m 1/1 Running 0 18s dev
web-5f9ccb876d-clnwv 1/1 Running 0 18s production
web-5f9ccb876d-jprz2 1/1 Running 0 18s staging
web-5f9ccb876d-lsjpj 1/1 Running 0 18s dev

The -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:

Terminal window
kubectl label pod "$POD1" debug=oui
kubectl get pods -l debug=oui
kubectl delete pod "$POD1"
kubectl rollout status deployment/web --timeout=90s
kubectl get pods -l app=web -L debug
Output
pod/web-5f9ccb876d-clnwv labeled
NAME READY STATUS RESTARTS AGE
web-5f9ccb876d-clnwv 1/1 Running 0 18s
pod "web-5f9ccb876d-clnwv" deleted from default namespace
deployment "web" successfully rolled out
NAME READY STATUS RESTARTS AGE DEBUG
web-5f9ccb876d-288zb 1/1 Running 0 2s
web-5f9ccb876d-jprz2 1/1 Running 0 20s
web-5f9ccb876d-lsjpj 1/1 Running 0 20s

The 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:

Terminal window
kubectl patch deployment web -p '{"spec":{"template":{"metadata":{"labels":{"debug":"oui"}}}}}'
kubectl rollout status deployment/web --timeout=90s
kubectl get pods -l debug=oui
Output
deployment.apps/web patched
Waiting 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 out
NAME READY STATUS RESTARTS AGE
web-56d9f7695d-shcjg 1/1 Running 0 1s
web-56d9f7695d-tkksh 1/1 Running 0 1s
web-56d9f7695d-v8dnh 1/1 Running 0 2s

This 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:

Terminal window
kubectl label deployment web team=web
kubectl get deployments --show-labels
kubectl get pods -l team=web
Output
deployment.apps/web labeled
NAME READY UP-TO-DATE AVAILABLE AGE LABELS
api 2/2 2 2 22s app=api
web 3/3 3 3 22s app=web,team=web
No 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.

PartRule
Key name63 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)
Value63 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:

Terminal window
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-valide
Output
error: 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 bytes

If the information does not fit these rules, it belongs in an annotation.

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.

LabelRoleExample
app.kubernetes.io/nameName of the applicationboutique
app.kubernetes.io/instanceSpecific instance of the applicationboutique-prod
app.kubernetes.io/versionVersion of the application2.4.1
app.kubernetes.io/componentRole in the architecturefrontend, database
app.kubernetes.io/part-ofOverall applicationsite-marchand
app.kubernetes.io/managed-byTool that manages the objecthelm, 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.

Terminal window
kubectl apply -f - <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: boutique
labels:
app.kubernetes.io/name: boutique
app.kubernetes.io/version: "2.4.1"
app.kubernetes.io/component: frontend
spec:
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:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
EOF
kubectl rollout status deployment/boutique --timeout=90s
kubectl get pods -l app.kubernetes.io/name=boutique --show-labels
Output
deployment.apps/boutique created
Waiting 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 out
NAME READY STATUS RESTARTS AGE LABELS
boutique-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-b
boutique-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-a

The 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.

Terminal window
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" --overwrite
kubectl annotate deployment web ticket-
Output
deployment.apps/web annotated
deployment.apps/web annotated
error: --overwrite is false but found the following declared annotation(s): 'owner' already has a value (equipe-web@exemple.fr)
deployment.apps/web annotated
deployment.apps/web annotated

The 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.

Terminal window
kubectl describe deployment web | grep -A4 '^Annotations:'
kubectl get deployment web -o jsonpath='{.metadata.annotations.owner}{"\n"}'
kubectl get deployments -l owner
Output
Annotations: deployment.kubernetes.io/revision: 2
owner: equipe-sre@exemple.fr
runbook: https://wiki.exemple.fr/runbooks/web
Selector: app=web
Replicas: 3 desired | 3 updated | 3 total | 3 available | 0 unavailable
equipe-sre@exemple.fr
No 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.

AnnotationWho sets itWhat it is for
deployment.kubernetes.io/revisionthe Deployment controllernumber of the current revision
kubectl.kubernetes.io/last-applied-configurationkubectl applycopy of the last applied manifest, to compute the next change
kubernetes.io/change-causeyoureason 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.

Terminal window
kubectl delete deployment web api boutique
kubectl get pods
Output
deployment.apps "web" deleted from default namespace
deployment.apps "api" deleted from default namespace
deployment.apps "boutique" deleted from default namespace
NAME READY STATUS RESTARTS AGE
api-698865cd4b-plfwg 1/1 Terminating 0 24s
api-698865cd4b-vwm6m 1/1 Terminating 0 24s
boutique-548bc488fb-75fqx 1/1 Terminating 0 2s
boutique-548bc488fb-gxgwp 1/1 Terminating 0 2s
web-56d9f7695d-shcjg 1/1 Terminating 0 3s
web-56d9f7695d-tkksh 1/1 Terminating 0 3s
web-56d9f7695d-v8dnh 1/1 Terminating 0 4s

Troubleshooting

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.

SymptomLikely causeSolution
invalid label valueValue of more than 63 characters, or spaces and forbidden charactersShorten it, or switch to an annotation
'env' already has a value (...), and --overwrite is falseThe label already existsAdd --overwrite
--overwrite is false but found the following declared annotation(s)The annotation already existsAdd --overwrite
-l returns nothingLabel absent, typo, or objects in another namespaceCheck with kubectl get pods --show-labels
The label set on a Pod has disappearedThe Pod was recreated from the template of the DeploymentWrite the label in spec.template.metadata.labels
kubectl label deployment does not change the PodsThe Pods take the labels of the template, not of the DeploymentChange 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 label and kubectl annotate share the syntax: --overwrite to replace, trailing dash (env-) to remove.
  • -l app=web,env=production combines conditions with "and"; env!=x also keeps objects without the env key.
  • --show-labels displays all the labels, -L env turns one into a column; annotations are read with describe or 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

6 questions
5 min
80% to pass

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