Lesson 28 · Section 3: Scheduling
Lesson 28: Labels and selectors: how Kubernetes objects find each other
What labels are and what they are not, how equality-based and set-based selectors pick objects, where Services, Deployments and the scheduler use them, and the kubectl habits that find a broken selector in seconds. · 20 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why labels exist
A cluster quickly fills with objects: hundreds of Pods, dozens of Deployments and Services, a handful of nodes. Two needs appear at once:
- You need to slice that pile in different ways: "everything of the shop team", "all production Pods", "the frontends, but not the canary".
- Kubernetes itself needs to connect objects: which Pods does this Service send traffic to? Which Pods does this ReplicaSet own? Which nodes may this Pod run on?
Names cannot do this. A name identifies exactly one object, and Pods come and go with random names. A fixed hierarchy (team, then app, then environment) would not work either, because every question cuts across it differently.
So Kubernetes uses the same idea as tags on photos: attach small labels to each object, and ask questions with selectors.
What a label is
Parts:
- Service web (selector: app=web)
- ReplicaSet web (selector: app=web)
- Pod web-1 (app=web)
- Pod web-2 (app=web)
- Pod db-1 (app=db)
Connections:
- Service web to Pod web-1: app=web
- Service web to Pod web-2
- ReplicaSet web to Pod web-1
- ReplicaSet web to Pod web-2: app=web
Labels live in metadata.labels of any object, Pods, nodes, namespaces and Services alike:
metadata:
name: web-1
labels:
app: web
tier: frontend
env: prod
Kubernetes attaches no meaning to app, tier or env. They mean something only because a selector somewhere asks
for them. Several objects can carry the same label (that is the whole point), and each key can appear only once per
object.
The syntax is strict, because labels are indexed and queried:
| Part | Rules |
|---|---|
| Key name | 63 characters at most. Letters, digits, -, _ and ., starting and ending with a letter or digit |
| Key prefix (optional) | A DNS subdomain and a slash before the name, such as app.kubernetes.io/name. 253 characters at most |
| Value | 63 characters at most, same characters as the name, and it may be empty |
Keys without a prefix are yours. The prefixes kubernetes.io/ and k8s.io/ are reserved for Kubernetes, which
uses them for labels it sets itself:
| Label | Set on | By |
|---|---|---|
kubernetes.io/hostname, kubernetes.io/os, kubernetes.io/arch | Nodes | The kubelet |
topology.kubernetes.io/zone, topology.kubernetes.io/region | Nodes | The cloud provider integration |
node-role.kubernetes.io/control-plane | Control plane nodes | kubeadm |
kubernetes.io/metadata.name | Namespaces | The API server |
pod-template-hash | ReplicaSets and Pods of a Deployment | The Deployment controller |
kubernetes.io/service-name | EndpointSlices | The EndpointSlice controller |
Labels or annotations?
metadata.annotations looks the same, a map of keys and values, but serves the opposite purpose.
| Labels | Annotations | |
|---|---|---|
| Purpose | Identify and group objects | Attach information to an object |
| Can be selected on | Yes | No |
| Values | Short, restricted characters | Any string, up to 256 KiB for all annotations together |
| Typical content | app, tier, env, version | Build ids, contact details, tool settings, the change cause of a rollout |
The rule of thumb: if something will ever ask "give me all objects where...", it is a label. Everything else is an annotation.
How selectors work
Parts:
- Selector (env=prod,tier=web)
- Pod web-1 (env=prod, tier=web)
- Pod web-2 (env=dev, tier=web)
- Pod db-1 (env=prod, tier=db)
Connections:
- Selector to Pod web-1: both match
- Selector to Pod web-2: no
- Selector to Pod db-1: env only
A selector is a list of conditions. All of them must hold: the comma means AND, and there is no OR between conditions.
There are two kinds of condition, and you can mix them.
| Kind | Written as | Selects objects where |
|---|---|---|
| Equality | env=prod or env==prod | env is prod |
| Equality | env!=dev | env is not dev, or there is no env label at all |
| Set | env in (prod,qa) | env is prod or qa |
| Set | tier notin (db,cache) | tier is neither, or there is no tier label |
| Set | gpu | A gpu label exists, whatever its value |
| Set | !gpu | No gpu label exists |
in is how you get an OR, but only between values of one key. "Pods of the shop team or Pods in prod" cannot be
written as one selector.
Inside manifests the same conditions appear in two shapes.
The plain map, used by Services (and the old ReplicationController). Equality only:
spec:
selector:
app: web
tier: frontend
The label selector, used by Deployments, ReplicaSets, DaemonSets, StatefulSets, Jobs, NetworkPolicies, PersistentVolumeClaims and others. It has two fields, and everything in both is ANDed:
spec:
selector:
matchLabels:
app: web
matchExpressions:
- { key: env, operator: In, values: [prod, qa] }
- { key: canary, operator: DoesNotExist }
The operators are In, NotIn, Exists and DoesNotExist. matchLabels is only a shorter way to write In
with a single value. Node affinity, later in this section, uses the same expressions on node labels and adds Gt
and Lt.
Under the hood · What the API server does with a selector
Labels are stored with the object in etcd; there is no separate label database. When you run
kubectl get pods -l app=web, kubectl sends GET /api/v1/namespaces/default/pods?labelSelector=app%3Dweb, and the
API server returns only the objects that match.
Controllers do not ask again and again. They keep a watch open on the kinds they care about and hold a local copy of every object. When a Pod appears, changes its labels or disappears, the controller is told and re-evaluates its selector against the copy. That is why a label change takes effect within moments: the EndpointSlice controller drops the Pod from the Service, and the ReplicaSet controller starts a replacement.
A selector only ever sees objects in its own namespace. A Service in shop never selects Pods in data, even
with identical labels. The exceptions select other kinds of thing: a NetworkPolicy's namespaceSelector selects
namespaces by their labels, and node selectors select nodes, which have no namespace.
Under the hood · Empty selectors: everything or nothing?
It depends on the object, so read the field's description with kubectl explain when it matters.
- In a label selector (
matchLabels/matchExpressions), an empty selector{}matches everything.podSelector: {}in a NetworkPolicy means "all Pods in this namespace". - A Service with no
selectorselects nothing: Kubernetes creates no EndpointSlices for it, and you are expected to provide the backends yourself. kubectl get pods -l ''and no-lat all both list everything.
Where Kubernetes uses them
| Object | Field | What it selects |
|---|---|---|
| Service | spec.selector (plain map) | The Pods that receive its traffic |
| Deployment, ReplicaSet, DaemonSet, StatefulSet, Job | spec.selector | The Pods the controller owns and counts |
| NetworkPolicy | spec.podSelector, namespaceSelector | The Pods a rule applies to, and who may talk to them |
| PodDisruptionBudget | spec.selector | The Pods protected during node drains |
| Pod | spec.nodeSelector, spec.affinity | The nodes the Pod may be scheduled on |
| Pod | topologySpreadConstraints, pod affinity | Other Pods to spread away from or sit next to |
| PersistentVolumeClaim | spec.selector | The PersistentVolumes it may bind to |
This is why the lesson sits at the start of the Scheduling section. Node selectors, node affinity, pod affinity and spread constraints in the next lessons are all selectors over the labels of nodes or Pods.
Three places in one Deployment
Parts:
- Deployment web (labels: team=shop)
- spec.selector (app=web)
- template labels (app=web, tier=front)
- Pods (app=web, tier=front)
- Service web (selector: app=web)
Connections:
- Deployment web to spec.selector: has
- spec.selector to template labels: must match
- template labels to Pods: copied
- Service web to Pods: selects
A Deployment manifest contains labels three times, and each has a different job:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
labels:
team: shop # 1. labels OF the Deployment: for you, with kubectl get deploy -l
spec:
replicas: 3
selector:
matchLabels:
app: web # 2. the selector: which Pods this Deployment owns
template:
metadata:
labels:
app: web # 3. labels stamped on every Pod; must satisfy the selector
tier: frontend # extra labels are fine
spec:
containers:
- name: nginx
image: nginx:1.29
Two rules are enforced by the API server:
- The selector must match the template's labels. Otherwise the Deployment would create Pods it does not
recognise, forever. The error is
`selector` does not match template `labels`. - The selector is immutable in
apps/v1. To change it, delete the Deployment and create it again. The template's labels can change, as long as they still satisfy the selector, and changing them starts a rollout.
The Deployment's own labels (1) need not resemble the others at all. A Service selecting team: shop here would
find no Pods, because no Pod carries that label.
A label change is an action
Parts:
- ReplicaSet web (wants 3, app=web)
- Pod web-1 (app=web)
- Pod web-2 (app=web)
- Pod web-4 (new, app=web)
- Pod web-3 (now app=debug)
Connections:
- ReplicaSet web to Pod web-1
- ReplicaSet web to Pod web-2: counts
- ReplicaSet web to Pod web-4: creates
- ReplicaSet web to Pod web-3: no match
Because selectors are evaluated continuously, editing a label on a live Pod is not cosmetic. Take a Pod out of
app=web and, within a second or two:
- the Service removes it from its EndpointSlices, so it receives no new traffic;
- the ReplicaSet sees one Pod too few and creates a replacement;
- the Pod itself keeps running, now owned by nobody. Nothing will restart or delete it for you.
That is useful when one replica misbehaves: relabel it, let the ReplicaSet restore capacity, and debug the isolated Pod at leisure. Delete it by hand when you are done.
Using it
Example · Label objects and read the labels back
kubectl run web-1 --image=nginx:1.29 --labels="app=web,env=prod" # labels at creation
kubectl label pod web-1 tier=frontend # add a label
kubectl label pod web-1 env=qa --overwrite # change an existing one
kubectl label pod web-1 tier- # remove: key and a minus sign
kubectl get pods --show-labels # every label, one column
kubectl get pods -L app,env # one column per chosen key
Without --overwrite, changing a label fails with
'env' already has a value (prod), and --overwrite is false. That is a safety net, not a bug.
Nodes and namespaces are labelled the same way: kubectl label node node-1 disktype=ssd,
kubectl label namespace shop team=storefront.
Example · Select with -l
kubectl get pods -l app=web # equality
kubectl get pods -l app=web,env=prod # AND
kubectl get pods -l 'env!=prod' # not prod, including Pods with no env label
kubectl get pods -l 'env in (prod,qa),tier notin (db)'
kubectl get pods -l 'canary' # the key exists
kubectl get pods -l '!canary' # the key does not exist
kubectl get all -l app=web # several kinds at once
kubectl get pods -A -l app=web # every namespace
kubectl delete pods -l env=dev # act on the whole group
kubectl label pods -l app=web release=stable # label the whole group
-l is short for --selector, and it works on almost every kubectl verb: get, describe, delete, label,
annotate, logs, top, wait. Quote anything with spaces, brackets or !, or the shell will interpret it.
Example · A Service that finds its Pods
The task: three web Pods already run with the labels app=web,tier=frontend. Expose them inside the cluster on
port 80.
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
tier: frontend
ports:
- port: 80
targetPort: 80
kubectl apply -f web-svc.yaml
kubectl get service web -o wide # the SELECTOR column
kubectl get endpointslices -l kubernetes.io/service-name=web # three addresses expected
When the Pods belong to a Deployment, kubectl expose deployment web --port=80 writes the same Service and copies
the Deployment's selector for you, which rules out typing mistakes.
Example · Find why a Service has no endpoints
kubectl describe service web shows Endpoints: empty. The Pods are Running. Compare the two sides:
kubectl get service web -o jsonpath='{.spec.selector}' # {"app":"web","tier":"front"}
kubectl get pods --show-labels # app=web,tier=frontend
kubectl get pods -l app=web,tier=front # No resources found
The selector asks for tier=front, the Pods say tier=frontend. Fix whichever side the task tells you to. A
Service's selector, unlike a Deployment's, can be edited in place:
kubectl set selector service web 'app=web,tier=frontend'
kubectl get endpointslices -l kubernetes.io/service-name=web
Example · Label a node and send a Pod to it
A first taste of what the rest of this section builds on:
kubectl label node node-2 disktype=ssd
kubectl get nodes -l disktype=ssd
apiVersion: v1
kind: Pod
metadata:
name: fast-db
spec:
nodeSelector:
disktype: ssd
containers:
- name: db
image: postgres:18
The scheduler filters out every node without disktype=ssd. If no node carries the label, the Pod stays Pending
with the event node(s) didn't match Pod's node affinity/selector.
Tricks
Common mistakes
- Labelling the Deployment and expecting the Pods to change.
kubectl label deployment web tier=frontendsets label number 1 only. Pods get their labels from the template:kubectl edit deployment weband changespec.template.metadata.labels, which rolls out new Pods. - Selector and template that disagree. The Deployment is rejected at creation. When you rename
app: web, rename it in both places. - Trying to edit a Deployment's selector.
field is immutable. Delete and recreate, or leave the selector alone and add labels to the template instead. - One character off.
app: webandapp: Web, ortier: frontandtier: frontend, are different labels. Nothing warns you: the Service simply has no endpoints. - Forgetting that every condition must hold. A Service selector with three labels matches only Pods carrying all three. Adding a label to a selector narrows it; adding a label to a Pod never removes it from a group.
- Expecting
!=to require the label.env!=prodalso matches objects with noenvlabel. Write'env,env!=prod'to demand that the key exists. - Unquoted set-based selectors.
kubectl get pods -l env in (prod,qa)is a shell syntax error. Put the selector in single quotes. - A selector that is too wide.
kubectl delete pods -l appdeletes every Pod that has anapplabel. Run the same selector withgetfirst. - Putting data in labels. A description, a URL or a JSON blob will not pass the 63-character rule and has no business being queried. Use an annotation.
Recap
- A label is a key and value pair in
metadata.labels; a selector is a query over labels. Objects are connected by selectors, not by lists. - Conditions are joined by AND. Equality:
=,!=. Set:in,notin, key exists,!key. - Services use a plain map (equality only). Deployments and friends use
matchLabelsandmatchExpressions. - A Deployment's selector must match its template's labels and is immutable. Its own
metadata.labelsselect nothing. - Selectors are evaluated continuously: relabel a Pod and it leaves its Service and its ReplicaSet at once.
- In the exam:
--show-labels,-l,kubectl label ... --overwrite,key-to remove, and compare the Service's selector with the Pods' labels whenever endpoints are missing.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Shape kubectl's output with jsonpath, custom columns, sorting and field selectors to answer four questions about a cluster without scrolling through YAML.
Investigate · Level 2 · standard · target 20 min
Use labels and selectors to count workloads, repair a Service that selects nothing, take one pod out of rotation and label pods that do not exist yet.
Fix · Level 2 · standard · target 20 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.