Kubernetes foundations: the cluster and kubectl · 6 MIN READ

Labels and selectors: how controllers and Services find their pods

Label objects, query them with equality-based and set-based selectors, explain how ReplicaSets and Services choose pods by label, and predict what relabelling a pod does.

Kubernetes has no fixed links between a ReplicaSet and its pods or between a Service and its backends; they find each other through labels, and the match is evaluated continuously. That makes the system flexible, because changing one label can pull a pod out of rotation. It also makes it fragile when two selectors overlap or a label changes by accident.

kubernetes · A MAP OF THE IDEA

  1. Choose stable selector labels
  2. Stamp them in the template
  3. Query with -l and -L
  4. Relabel to quarantine a pod

Useful when

  • Loose coupling lets one label change move a pod in or out of rotation.
  • One selector language serves kubectl, controllers, Services and policies.

Watch out

  • Overlapping selectors make controllers adopt, or Services route to, the wrong pods.
  • Workload selectors are immutable; a wrong one means a new object.

Implementation & operation cost: A labelling convention agreed up front and discipline about which labels go into selectors.

01

Labels and the selector language

A label is a key-value pair in metadata.labels, and keys may carry a DNS prefix such as app.kubernetes.io/name. Selectors come in two forms. Equality-based: app=web, and app!=web, which also matches objects without an app label. Set-based: app in (web,cache), tier notin (backend), tier for objects that have the key, and !tier for objects that do not. Commas mean AND and there is no OR across keys; in on a single key is the only way to accept several values. kubectl get -l accepts both forms, --show-labels appends every label, and -L app,tier (long form --label-columns) adds one column per key. In manifests, a Service takes a plain map matched by equality, while ReplicaSets, Deployments, Jobs and NetworkPolicies take matchLabels and matchExpressions.

bash
kubectl get pods --show-labels
kubectl get pods -l app=web
kubectl get pods -l 'app in (web,cache),tier!=backend'
kubectl get pods -l '!tier' --label-columns=app,tier
Read the code

Quote set-based selectors so that the shell does not interpret the parentheses or the exclamation mark. The third command matches pods labelled web or cache unless they have tier=backend, so pods without any tier label match too. The fourth lists only pods without a tier label and shows their app and tier values as columns, the second of them empty.

02

matchLabels and matchExpressions

Workload controllers use a LabelSelector: matchLabels for exact values and matchExpressions with the operators In, NotIn, Exists and DoesNotExist; every condition must hold. The pod template's labels must satisfy the selector, or the API server rejects the object with selector does not match template labels. A Deployment adds a pod-template-hash label to the selector and pods of each ReplicaSet it creates, so the ReplicaSets of different revisions never claim each other's pods. Keep selectors narrow. A ReplicaSet adopts any pod without an owner that matches its selector, so a hand-made pod with the same labels is counted, and the ReplicaSet deletes a pod to get back to its number. A Service whose selector matches two workloads sends traffic to both.

yaml
apiVersion: apps/v1
kind: ReplicaSet
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app: web
    matchExpressions:
    - key: track
      operator: In
      values: [stable, canary]
  template:
    metadata:
      labels:
        app: web
        track: stable
    spec:
      containers:
      - name: nginx
        image: nginx:1.27
Read the code

This ReplicaSet keeps three pods that carry app=web and a track label of stable or canary. Its template stamps app=web and track=stable on every pod it creates, which satisfies both conditions, and kubectl get rs -o wide prints the selector as app=web,track in (stable,canary). In practice you create Deployments rather than ReplicaSets, but their selector field has exactly this shape.

03

Who selects by label, and when

Selection is live. The ReplicaSet controller compares the pods that match its selector with spec.replicas whenever something changes: it adopts matching pods that have no controller, and it releases pods it owns that stop matching by removing its ownerReference from them. The EndpointSlice controller recomputes a Service's endpoints from its selector, and only Ready pods among them receive traffic. NetworkPolicies, PodDisruptionBudgets and topology spread constraints select pods by label as well. The consequences are direct: a label changed by hand takes effect everywhere at once; a stray pod created with app=web may be adopted by an existing ReplicaSet; and a Service whose selector matches two Deployments balances across both, which is how some canary releases work on purpose and how many outages happen by accident.

04

Taking a pod out of its ReplicaSet

Relabelling is the standard way to quarantine a misbehaving pod without killing it. Change app=web to app=debug and three things happen. The ReplicaSet no longer matches the pod, releases it and, now one short, creates a replacement. The Service drops the pod's IP from its endpoints, so it receives no new requests. The pod itself keeps running untouched, with its memory and logs intact for exec, logs or port-forward. When you are done, delete it; it no longer has an owner, so nothing else will. Do not relabel it back, because the ReplicaSet would adopt it, count one pod too many and delete one. The GopherForge lab models the release and the replacement too.

bash
POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
kubectl label pod $POD app=debug --overwrite
kubectl get pods --label-columns=app
kubectl get endpoints web
Read the code

On a real cluster, get pods then shows four pods from the web ReplicaSet's template: the quarantined one with APP debug and three with web, one of them only seconds old. get endpoints web lists the IPs of the three web pods only. The first line stores a pod name in a shell variable, a common pattern because pod names carry random suffixes.

05

Why a Deployment's selector is immutable

In apps/v1, spec.selector of a Deployment, ReplicaSet, StatefulSet or DaemonSet cannot change after creation; an update fails with spec.selector ... field is immutable. The reason is ownership: a new selector could suddenly match another workload's pods, or orphan every pod the controller runs, and there is no safe automatic answer to either. Template labels may change as long as they still satisfy the selector, and you can add labels to the template freely. To change a selector, create a new Deployment under a new name, move traffic to it, and delete the old one. So choose selector labels on day one that will never need to change, such as app.kubernetes.io/name and app.kubernetes.io/instance, and keep version or track labels out of the selector.

06

Try it in the lab terminal

Run two Deployments and expose one of them as a Service, query their pods with both selector forms, and look at the selector each ReplicaSet uses. Then quarantine one web pod by relabelling it and watch the Service's endpoints shrink, the Service side of the story above. The last command tries to change the Deployment's selector and is meant to fail, because the API server refuses it.

bash
kind create cluster
kubectl create deployment web --image=nginx:1.27 --replicas=3
kubectl create deployment cache --image=redis:7
kubectl rollout status deploy/web
kubectl expose deployment web --port=80
kubectl get pods --show-labels
kubectl get pods -l 'app in (web,cache)' --label-columns=app
kubectl get rs -o wide
kubectl get endpoints web
POD=$(kubectl get pods -l app=web -o jsonpath='{.items[0].metadata.name}')
kubectl label pod $POD app=debug --overwrite
kubectl get endpoints web
kubectl patch deployment web -p '{"spec":{"selector":{"matchLabels":{"app":"web2"}},"template":{"metadata":{"labels":{"app":"web2"}}}}}'
Read the code

--show-labels reveals the pod-template-hash label each Deployment added beside app, and get rs -o wide shows it inside each ReplicaSet's selector, as in app=web,pod-template-hash=<hash>. The set-based query lists the three web pods and the cache pod with an APP column. get endpoints web starts with three pod IPs on port 80; after one pod is relabelled to app=debug it lists two. On a real 1.34 cluster get endpoints also warns that v1 Endpoints is deprecated in favour of EndpointSlices. The patch fails with The Deployment "web" is invalid: spec.selector: Invalid value: ... field is immutable.

TAKE THIS WITH YOU

Selectors, not links, connect controllers and Services to pods, and they are evaluated continuously, so a label change takes effect everywhere at once. Pick narrow, stable selector labels at creation, because a Deployment's selector can never change.

Check your understanding

A web pod misbehaves and you change its label from app=web to app=debug. Its ReplicaSet wants 3 replicas, and a Service selects app=web. What happens next?

Go to the source

Progress stays in this browser. No account needed.