Labels, selectors and annotations
Group objects with labels, find them with selectors, and park everything else in annotations.
Open this lesson in the learning hubKey points
- A label is a key=value tag used for selection. Services, Deployments and
kubectl -lall work by matching labels. - A selector is an AND of every pair listed. Miss one label on the pod and it silently never becomes an endpoint.
matchExpressionsaddsIn,NotInandExistswhen a flat equality match is not enough.- Annotations are never selectable. They carry data for tools: ingress settings, config checksums, an owning team.
- Use the recommended keys such as
app.kubernetes.io/nameand/versionso dashboards can group your objects. - A Deployment's
selectoris immutable. Getting it wrong means delete and recreate, so pick the labels before you ship.
Example
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders
annotations:
owner: payments-team@acme.io # data, never matched on
spec:
selector:
matchLabels: # immutable once created
app.kubernetes.io/name: orders
tier: api
template:
metadata:
labels: # must contain every selector pair
app.kubernetes.io/name: orders
app.kubernetes.io/version: 1.4.2
tier: api
---
# ad-hoc selection from the command line
# kubectl get pods -l 'app.kubernetes.io/name=orders,tier!=canary'
# kubectl label pod orders-7d9f8c-4xk2p tier=canary --overwrite
Labels are what machines match on. Annotations are what humans and tools read.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Kubernetes course, and every lesson in it is listed on the Kubernetes contents page.