Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 78 ยท Pods

Labels, Selectors and Annotations

Learn label syntax, equality and set-based selectors, the recommended app.kubernetes.io labels, and when to use annotations instead of labels.

Kubernetes objects do not point at each other by name. A Service does not hold a list of Pod names, and a Deployment does not remember its Pods one by one. Instead, objects carry small key-value tags called labels, and other objects find them with a selector: a query such as "every Pod where app is web and tier is frontend". This loose coupling is one of the best ideas in Kubernetes, because Pods come and go all the time, and a query always finds the current ones.

This lesson covers how labels are written, the two selector styles, how selectors appear in manifests and on the command line, the recommended standard labels, and how annotations differ. A Python stand-in implements the selector matching rules so you can test your queries. If you have not seen a manifest before, read YAML and the Shape of a Manifest first.

Manifests and commands here are read-only examples. The Python code is a model of selector matching, not Kubernetes itself.

Labels connect everything

Label A key-value tag on an object.
Selector A query over labels.
Link Services, Deployments and policies use selectors.
1 / 2

Labels

Labels live under metadata.labels on any object:

YAML
apiVersion: v1
kind: Pod
metadata:
  name: web-7d4b9
  labels:
    app: web
    tier: frontend
    environment: production
    version: "2.4.1"
spec:
  containers:
    - name: web
      image: example/web:2.4.1

There are no required labels and no meaning built in (with a few exceptions Kubernetes itself adds, such as pod-template-hash on Pods made by a Deployment). You choose keys that fit your organization: team, environment, application, release track, cost center.

The rules for keys and values

A label key has an optional prefix and a name, separated by a slash: example.com/team.

  • The name is at most 63 characters, made of letters, digits, -, _ and ., and must start and end with a letter or digit.
  • The optional prefix must be a DNS subdomain (at most 253 characters). Prefixes starting with kubernetes.io/ and k8s.io/ are reserved for Kubernetes. Without a prefix, the key is assumed to be private to the user.

A label value follows the same character rules as a name, at most 63 characters, but it can be empty. Values are always strings: write version: "2.4" and enabled: "true" in quotes, or YAML turns them into numbers and booleans and the API server rejects them.

Because values are short and restricted, labels are not the place for free text, URLs with slashes or long identifiers. Those belong in annotations.

Selectors

A selector is a set of requirements, and an object matches only if it satisfies all of them. There are two styles.

Equality-based

Equality-based selectors compare a key with a value:

Requirement Matches objects where
app=web or app==web label app exists and equals web
tier!=backend label tier is absent or different from backend

The trap is !=: it also matches objects that have no tier label at all.

Set-based

Set-based selectors are more expressive:

Requirement Matches objects where
environment in (production, staging) the label exists and its value is one of the listed values
environment notin (dev) the label is absent or has another value
canary the label key exists (any value)
!canary the label key does not exist

Commas between requirements mean AND. There is no OR between whole requirements: to express "A or B" use in.

On the command line

kubectl accepts selector strings with -l or --selector:

Terminal
kubectl get pods -l app=web
kubectl get pods -l 'app=web,tier!=backend'
kubectl get pods -l 'environment in (production,staging)'
kubectl get pods -l '!canary'
kubectl get pods --show-labels
kubectl label pod web-7d4b9 canary=true
kubectl label pod web-7d4b9 canary-

The last two lines add and remove a label (a trailing - removes it). Changing labels on a live Pod is a legitimate debugging trick: relabel a misbehaving Pod and it drops out of its Service and ReplicaSet, which then makes a replacement, leaving the sick Pod for you to investigate.

In manifests

In YAML, older objects such as Services use a simple map of equality requirements, while Deployments, ReplicaSets, Jobs and NetworkPolicies use a richer LabelSelector with two parts:

YAML
# Service: equality only
spec:
  selector:
    app: web
    tier: frontend
YAML
# Deployment, ReplicaSet and others: matchLabels + matchExpressions
spec:
  selector:
    matchLabels:
      app: web
    matchExpressions:
      - key: environment
        operator: In
        values: [production, staging]
      - key: canary
        operator: DoesNotExist

The four operators are In, NotIn, Exists and DoesNotExist. matchLabels is just a shorthand for In with one value. All entries are ANDed together. An empty selector (selector: {}) selects every object in some APIs and none in others, so be careful with it.

A frequent mistake in Deployments: the selector must match the Pod template's labels, and it cannot be changed after the Deployment is created. If they differ, the API server rejects the manifest (Deployments).

A selector matcher in Python

This stand-in parses both selector syntaxes and evaluates them against a list of Pods, following the rules above (including the != and notin behavior for missing keys).

Python A label selector matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check two lines against the rules. tier!=backend also returns job-1, which has no tier label at all, and environment notin (staging) returns job-1 for the same reason. If you want only Pods that have a tier other than backend, combine requirements: tier,tier!=backend.

Using labels in the real world: Services and Deployments

Labels are how the main objects hang together:

  • A Service selects Pods by label and sends traffic only to the ready ones (Services).
  • A ReplicaSet and Deployment count the Pods that match their selector, and create or delete Pods to reach the desired number (ReplicaSets).
  • A NetworkPolicy chooses which Pods it protects, and which peers may talk to them (Network Policies).
  • Scheduling rules like node affinity and topology spread use label selectors on nodes and Pods (Node Selectors, Affinity and Anti-Affinity).
  • Humans and tools list and delete groups of objects: kubectl delete pods -l app=web.

Since a selector matches any object with the right labels, two different Deployments that accidentally share a label can fight over the same Pods. Make the label set that a selector uses specific enough to be unique, such as app.kubernetes.io/name plus app.kubernetes.io/instance.

Kubernetes documents a shared vocabulary under the app.kubernetes.io/ prefix, so that dashboards, Helm and other tools can understand your objects:

Label Meaning Example
app.kubernetes.io/name the application postgresql
app.kubernetes.io/instance a unique instance of it orders-db
app.kubernetes.io/version current version 16.4
app.kubernetes.io/component role in the architecture database
app.kubernetes.io/part-of the larger system shop
app.kubernetes.io/managed-by the tool that manages it helm

You do not have to use all of them, but name and instance for selectors, plus part-of and version for humans, are a good start. Keep labels that select stable. A selector label that changes with every release (for example the image tag) breaks the link between the Service and the Pods.

Annotations

Annotations also live under metadata, as a map, but they are for information rather than selection:

YAML
metadata:
  name: web
  annotations:
    description: "Public storefront, owned by the shop team. See the runbook."
    example.com/runbook: "https://wiki.example.com/runbooks/web"
    prometheus.io/scrape: "true"
    kubectl.kubernetes.io/last-applied-configuration: "{...}"

Differences from labels:

Labels Annotations
Purpose identify and select attach metadata
Can be selected on yes no
Value limits short (63 chars), restricted characters up to a total of 256 KB per object, any text
Typical content app, tier, environment URLs, build info, tool settings, JSON

Many tools read annotations as configuration. Ingress controllers use them for settings, kubectl apply stores the last applied configuration in one, and monitoring systems may use them to discover scrape targets. Because they are just strings with no schema, a typo in an annotation key is silently ignored, so check tool documentation carefully. As a rule: if you need to query by it, it is a label. If a human or a tool just needs to read it, it is an annotation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Service has selector app: web. Which Pods receive its traffic?

    Services pick Pods by label selector, in their own namespace, and only send traffic to ready ones. Names and annotations are not used.
  2. 2. Which Pods does the selector tier!=backend match?

    != also matches objects that lack the key. To require that the label exists, add the bare key as another requirement.
  3. 3. You want a label value true for a flag. How do you write it in YAML?

    Label values are strings. An unquoted true is parsed as a YAML boolean and the API server rejects it, so quote it.
  4. 4. Which is the right place for a long URL to a runbook?

    Label values are limited to 63 characters from a restricted set. Annotations hold arbitrary text and are intended for this kind of metadata.
  5. 5. How do you combine requirements in one selector?

    All requirements must hold. OR between values of the same key is expressed with the in operator.

Summary

  • Labels are key-value tags on metadata.labels. Keys have an optional DNS prefix, names and values are at most 63 characters, and values must be strings.
  • Selectors are ANDed requirements: equality (=, ==, !=) and set-based (in, notin, key, !key). != and notin also match objects that lack the key.
  • Services, ReplicaSets, Deployments, NetworkPolicies and scheduling rules all connect to Pods through label selectors, which kubectl -l also uses.
  • Use the app.kubernetes.io/* labels for a shared vocabulary and keep selector labels stable and specific.
  • Annotations hold non-identifying metadata of any length and cannot be selected on.

Next, learn how Kubernetes keeps a set of identical Pods running in ReplicaSets.