Labels & Selectors

Difficulty: Beginner

Question

What are labels and selectors in Kubernetes, and how do Services, Deployments and kubectl use them?

Answer

Labels are key/value pairs attached to Kubernetes objects (for example app: checkout, env: prod) and selectors are queries that pick objects by those labels. They are the glue of Kubernetes: Services find their Pods, Deployments and ReplicaSets know which Pods they own, and you filter resources with kubectl get pods -l app=checkout, all through labels rather than hard-coded names.

How labels connect objects

Kubernetes objects rarely reference each other by name. Instead:

  • A Service has spec.selector and routes to every Ready Pod whose labels match.
  • A Deployment has spec.selector.matchLabels, which must match the labels in its Pod template. The ReplicaSet counts matching Pods to decide whether to create or delete some.
  • A NetworkPolicy uses podSelector to decide which Pods a rule applies to.
  • Node affinity and nodeSelector match labels on nodes, such as topology.kubernetes.io/zone or node.kubernetes.io/instance-type.

This loose coupling is powerful. If you remove the app=checkout label from one misbehaving Pod, the Service stops sending it traffic and the ReplicaSet creates a replacement, while the old Pod stays alive for debugging.

Two kinds of selectors

KindSyntax exampleSupported by
Equality-basedapp=checkout,env!=devServices, nodeSelector, kubectl
Set-basedenv in (prod, staging), !canaryDeployments, ReplicaSets, Jobs, NetworkPolicy, kubectl

In YAML, set-based selectors use matchExpressions with operators In, NotIn, Exists and DoesNotExist. Multiple conditions are ANDed; there is no OR across keys.

Labels vs annotations

Both are key/value metadata, but only labels are indexed and selectable. Use labels for identifying, grouping and selecting (app, tier, version, team). Use annotations for non-identifying data that tools read: build commit SHA, owner contact, ingress controller options, Prometheus scrape hints. Label values are limited to 63 characters, while annotations can hold much larger values.

Conventions and gotchas

  • Use the recommended labels: app.kubernetes.io/name, app.kubernetes.io/instance, app.kubernetes.io/version, app.kubernetes.io/component, app.kubernetes.io/part-of, app.kubernetes.io/managed-by. Helm and dashboards understand them.
  • A Deployment's spec.selector is immutable after creation in apps/v1. Choose it carefully, and keep changing values like version out of the selector.
  • Two Deployments with overlapping selectors will fight over the same Pods. Keep selectors unique.
  • A typo between the Service selector and Pod labels gives a Service with no endpoints, a classic "connection refused" bug.
How a selector ties objects together. Services and controllers find Pods by matching labels, not by name.
  1. Pod labels app=checkout: Set in the Deployment's Pod template.
  2. ReplicaSet selector: Counts matching Pods and keeps the replica count.
  3. Service selector: Picks matching Pods that are Ready.
  4. EndpointSlice: Holds the IPs of the selected Pods.
  5. Traffic: Requests to the Service reach those Pods.

Code examples

Labels and both selector styles

apiVersion: apps/v1
kind: Deployment
metadata:
  name: checkout
spec:
  replicas: 3
  selector:
    matchLabels:
      app.kubernetes.io/name: checkout      # immutable after creation
    matchExpressions:
      - key: tier
        operator: In
        values: [backend]
  template:
    metadata:
      labels:
        app.kubernetes.io/name: checkout
        tier: backend
        version: v2.3.1                     # not in selector, safe to change
      annotations:
        git-commit: 9f2c1ab                 # metadata for humans and tools
    spec:
      containers:
        - name: app
          image: ghcr.io/acme/checkout:2.3.1

The selector uses only stable labels. The version label and commit annotation can change on every release without breaking the Deployment.

Filtering and relabelling with kubectl

kubectl get pods -l 'app.kubernetes.io/name=checkout,tier in (backend)'
kubectl get pods -L version            # show the label as a column
kubectl label pod checkout-abc12 quarantine=true
# Remove the selector label to pull a Pod out of the Service for debugging
kubectl label pod checkout-abc12 app.kubernetes.io/name-

The trailing minus removes a label. The ReplicaSet will notice one fewer matching Pod and start a replacement.

Key points

  • Labels identify and group; selectors query them. Annotations are not selectable.
  • Services use equality-based selectors; workloads support set-based matchExpressions.
  • A Deployment's selector is immutable in apps/v1.
  • Overlapping selectors between controllers cause them to fight over Pods.
  • Prefer the app.kubernetes.io/* recommended label set.

Common follow-up questions

  • What is the difference between a label and an annotation?
  • What happens if two Deployments have the same selector?
  • How would you remove one Pod from a Service without killing it?
  • Why should you not put the version label in a Deployment selector?

Interview tips

  • Call labels the glue of Kubernetes and give the Service-to-Pod example; it shows you understand loose coupling.
  • The 'remove a label to quarantine a Pod' trick is a memorable practical detail interviewers like.
  • Mention selector immutability; it is a real-world gotcha most beginners miss.

Concepts covered

Labels, Label Selectors, matchLabels, matchExpressions, Annotations

More Kubernetes & Orchestration questions