Labels, selectors and annotations

The tags that connect everything.

Beginner20 min · lesson 7 of 21
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (3 files, 1 KB): labels.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/k8s-fund/labels.tar.gz && tar -xzf labels.tar.gz, which creates ~/lab/labels/. SHA-256: af7d93faece46282be49b3b8210fa45070ca1ea8b40502c3094132b27a7b6940

In lesson 6, Deployments, a ReplicaSet kept four Pods running, even though their names were random and changed every time one was replaced. It never tracked those names. It looked for Pods carrying the label app=web, and counted them.

A label is a short key and value, like env=prod, attached to an object. A selector is a question about labels, such as "everything with app=web". ReplicaSets, Services and many kubectl commands find their Pods this way, so one wrong letter in a label can quietly cut an app off from its traffic.

Put labels on Pods

This file creates five small nginx Pods. Each has an app label, most have an env label, and one also has release=canary:

pods.yaml
apiVersion: v1
kind: Pod
metadata:
name: web-prod
labels:
app: web
env: prod
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
---
apiVersion: v1
kind: Pod
metadata:
name: web-staging
labels:
app: web
env: staging
release: canary
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
---
apiVersion: v1
kind: Pod
metadata:
name: api-prod
labels:
app: api
env: prod
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
---
apiVersion: v1
kind: Pod
metadata:
name: api-dev
labels:
app: api
env: dev
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
---
apiVersion: v1
kind: Pod
metadata:
name: toolbox
labels:
app: tools
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl apply -f pods.yaml && kubectl wait --for=condition=Ready pod --all --timeout=90s
pod/web-prod created pod/web-staging created pod/api-prod created pod/api-dev created pod/toolbox created pod/api-dev condition met pod/api-prod condition met pod/toolbox condition met pod/web-prod condition met pod/web-staging condition met
$ kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS api-dev 1/1 Running 0 23s app=api,env=dev api-prod 1/1 Running 0 23s app=api,env=prod toolbox 1/1 Running 0 23s app=tools web-prod 1/1 Running 0 23s app=web,env=prod web-staging 1/1 Running 0 23s app=web,env=staging,release=canary
$ kubectl get pods -L app,env
NAME READY STATUS RESTARTS AGE APP ENV api-dev 1/1 Running 0 26s api dev api-prod 1/1 Running 0 26s api prod toolbox 1/1 Running 0 26s tools web-prod 1/1 Running 0 26s web prod web-staging 1/1 Running 0 26s web staging

--show-labels adds a LABELS column with every label on each Pod. That gets hard to read once objects carry many labels, so -L app,env turns the keys you care about into columns of their own. The toolbox Pod has no env label, so its ENV cell is empty.

Select by equality

-l (short for --selector) keeps only the objects whose labels match. Commas mean "and":

ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl get pods -l env=prod
NAME READY STATUS RESTARTS AGE api-prod 1/1 Running 0 27s web-prod 1/1 Running 0 27s
$ kubectl get pods -l app=web,env!=prod
NAME READY STATUS RESTARTS AGE web-staging 1/1 Running 0 28s

env=prod found one api Pod and one web Pod. app=web,env!=prod asked for web Pods whose env is anything but prod, and only web-staging is left.

Select by set

Set-based selectors test a label against a list, or only check whether a key exists. Quote them, because the shell would otherwise read the brackets and the !:

ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl get pods -l 'env in (prod,staging)'
NAME READY STATUS RESTARTS AGE api-prod 1/1 Running 0 28s web-prod 1/1 Running 0 28s web-staging 1/1 Running 0 28s
$ kubectl get pods -l 'env notin (prod)' -L env
NAME READY STATUS RESTARTS AGE ENV api-dev 1/1 Running 0 29s dev toolbox 1/1 Running 0 29s web-staging 1/1 Running 0 29s staging
$ kubectl get pods -l '!release'
NAME READY STATUS RESTARTS AGE api-dev 1/1 Running 0 30s api-prod 1/1 Running 0 30s toolbox 1/1 Running 0 30s web-prod 1/1 Running 0 30s
$ kubectl get pods -l release -L release
NAME READY STATUS RESTARTS AGE RELEASE web-staging 1/1 Running 0 30s canary

Look closely at the notin result. toolbox is in it, with an empty ENV column. It has no env label at all, and "not in (prod)" is true for a Pod with no env. The same applies to !=. If you mean "has an env, and it is not prod", write env,env notin (prod). !release matched the four Pods without that key, and a bare release matched the one Pod that has it.

Labels can be added and removed on a running object. A trailing - removes a key:

ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl label pod toolbox env=dev && kubectl label pod web-staging release- && kubectl get pods -L env,release
pod/toolbox labeled pod/web-staging unlabeled NAME READY STATUS RESTARTS AGE ENV RELEASE api-dev 1/1 Running 0 33s dev api-prod 1/1 Running 0 33s prod toolbox 1/1 Running 0 33s dev web-prod 1/1 Running 0 33s prod web-staging 1/1 Running 0 33s staging

toolbox now has env=dev, and the RELEASE column is empty everywhere. Nothing restarted. A label is just data on the object.

How a ReplicaSet counts its Pods

Back to the ReplicaSet. It counts its Pods with its selector, so changing the label on one of them changes the count. Create a small Deployment and relabel one of its Pods:

ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl create deployment shop --image=nginx:1.30.6-alpine --replicas=2 && kubectl rollout status deployment/shop && kubectl get pods -l app=shop
deployment.apps/shop created Waiting for deployment spec update to be observed... Waiting for deployment spec update to be observed... Waiting for deployment "shop" rollout to finish: 0 out of 2 new replicas have been updated... Waiting for deployment "shop" rollout to finish: 0 of 2 updated replicas are available... Waiting for deployment "shop" rollout to finish: 1 of 2 updated replicas are available... deployment "shop" successfully rolled out NAME READY STATUS RESTARTS AGE shop-7d569854fb-4dptm 1/1 Running 0 12s shop-7d569854fb-d9g7h 1/1 Running 0 12s
$ kubectl label "$(kubectl get pods -l app=shop -o name | head -1)" app=debug --overwrite
pod/shop-7d569854fb-4dptm labeled
$ kubectl wait --for=condition=Ready pod -l app=shop --timeout=60s && kubectl get pods -l 'app in (shop,debug)' -L app
pod/shop-7d569854fb-d9g7h condition met pod/shop-7d569854fb-f22jr condition met NAME READY STATUS RESTARTS AGE APP shop-7d569854fb-4dptm 1/1 Running 0 18s debug shop-7d569854fb-d9g7h 1/1 Running 0 18s shop shop-7d569854fb-f22jr 1/1 Running 0 2s shop
$ kubectl get pods -l 'app in (shop,debug)' -o custom-columns=NAME:.metadata.name,APP:.metadata.labels.app,OWNER:.metadata.ownerReferences[0].kind
NAME APP OWNER shop-7d569854fb-4dptm debug <none> shop-7d569854fb-d9g7h shop ReplicaSet shop-7d569854fb-f22jr shop ReplicaSet

After the relabel there are three Pods. The one now labelled app=debug still runs, but the ReplicaSet no longer counts it, saw only one app=shop Pod, and started a new one, younger than the other two. The OWNER column shows the other side: the relabelled Pod has no owner any more. The ReplicaSet let go of it. This is a real debugging trick: pull a misbehaving Pod out of its ReplicaSet (and out of any Service that selects by the same label), and look at it in peace while a replacement takes over. You have to delete it yourself later, since nothing owns it.

A Service with a typo

A Service gives a group of Pods one stable address; lesson 8, Services, covers it properly. For now one fact matters: a Service picks its Pods by label, and sends traffic to every Pod its selector matches. This one has a typo in it:

web-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: wbe # typo: should be "web"
ports:
- port: 80
ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl apply -f web-svc.yaml && kubectl get endpointslice -l kubernetes.io/service-name=web
service/web created NAME ADDRESSTYPE PORTS ENDPOINTS AGE web-vz58n IPv4 <unset> <unset> 0s
$ kubectl get service web -o wide && kubectl get pods -l app=wbe
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR web ClusterIP 10.96.51.42 <none> 80/TCP 1s app=wbe No resources found in default namespace.

The Service was created without complaint. Its EndpointSlice, the list of Pod addresses the Service forwards to, shows <unset> under ENDPOINTS: no Pod matches the selector. kubectl get service -o wide prints the SELECTOR column, and asking for Pods with that exact selector returns No resources found. Those two commands together find this problem fastest. Kubernetes cannot warn you, because a selector that matches nothing yet is perfectly valid.

Fix the selector, then run kubectl get endpointslice -l kubernetes.io/service-name=web again until the ENDPOINTS column shows two addresses. It takes a second or two:

ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl set selector service web app=web
service/web selector updated
$ kubectl get service web -o wide && kubectl get endpointslice -l kubernetes.io/service-name=web
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR web ClusterIP 10.96.51.42 <none> 80/TCP 2s app=web NAME ADDRESSTYPE PORTS ENDPOINTS AGE web-vz58n IPv4 80 10.244.1.3,10.244.2.2 2s

kubectl set selector replaced the selector, and the EndpointSlice now lists two addresses, one for web-prod and one for web-staging. The Service kept its name and its cluster IP the whole time. Only the list of Pods behind it changed.

Annotations

Annotations are also key and value pairs on an object, but nothing selects by them. They are for information meant for people and tools: a contact, a ticket number, a build ID. Their values can be long and contain any text:

ubuntu@secopslog-k8s:~/lab/labels · Kubernetes 1.37
$ kubectl annotate pod web-prod team-contact='web-team@example.com' change-ticket='CHG-1042: raise worker count before the sale'
pod/web-prod annotated
$ kubectl describe pod web-prod | grep -A 2 '^Annotations'
Annotations: change-ticket: CHG-1042: raise worker count before the sale team-contact: web-team@example.com Status: Running
$ kubectl label pod web-prod note='raise worker count before the sale'
error: invalid label value: "note=raise worker count before the sale": 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])?')

kubectl describe lists both annotations. The same sentence as a label value is rejected: label values are limited to 63 characters of letters, digits, -, _ and ., and must start and end with a letter or digit. That limit is a good guide. If you would ever select by it, make it a label. If it is just something to read, make it an annotation. Lesson 10, Rolling updates, uses one, kubernetes.io/change-cause, to describe each release.

Hands-on

1. List the web and api Pods, leaving out dev: kubectl get pods -l 'app in (web,api),env notin (dev)' -L app,env.

2. List every Pod that has no env label: kubectl get pods -l '!env' -L app.

3. Clean up with kubectl delete -f pods.yaml -f web-svc.yaml, kubectl delete deployment shop and kubectl delete pod -l app=debug, then check with kubectl get pods.

What you should see: step 1 returns api-prod, web-prod and web-staging. api-dev is excluded, and toolbox is neither web nor api. Step 2 returns the three shop Pods, including the one labelled debug, because kubectl create deployment gave them no env label. After step 3, kubectl get pods says No resources found in default namespace.

Remember

ReplicaSets and Services find their Pods by selector, never by name, so a label typo silently leaves a Service with no endpoints. notin and != also match objects that lack the key.

Quick check
01A new Service gets no traffic. kubectl get endpointslice -l kubernetes.io/service-name=web shows <unset>. What do you check first?
Incorrect — kube-proxy uses the endpoints; it does not choose them. <unset> means no Pod matched.
Incorrect — A matching Pod that is not ready still appears in the slice, marked not ready.
Correct — -o wide showed app=wbe, and no Pod had that label.
Incorrect — The ports list on a container does not decide which Pods a Service selects.
02Pods are labelled env=prod, env=dev, and one has no env label. Which Pods does -l 'env notin (prod)' return?
Correct — A Pod without the key also satisfies notin; toolbox showed up with an empty ENV column.
Incorrect — This needs env,env notin (prod), which requires the key first.
Incorrect — The dev Pod has env=dev, which is not in (prod), so it matches too.
Incorrect — A Pod that lacks the key does not break the selector for the others.
03You change the app label on one Pod of a two-replica Deployment. What happens?
Incorrect — Kubernetes does not undo label edits. The relabelled Pod kept app=debug.
Incorrect — kubectl label succeeded. Ownership does not lock labels.
Incorrect — It counts by selector, and the Pod no longer matches.
Correct — The Pod lost its owner reference, and a third Pod appeared. In the lab the old one kept running.

Related