Labels & Selectors
Labels are key-value tags on objects; selectors query them to group and target resources.
Labels are the glue of Kubernetes. They are simple key-value pairs attached to objects, and almost every relationship in the cluster is expressed by matching them.
Examples of labels
app: web
tier: frontend
environment: production
version: v2Selectors
A selector is a query over labels. Deployments use them to find their Pods; Services use them to route traffic. Two forms exist:
- Equality:
app=web. - Set-based:
environment in (staging, production).
Why they matter
Get labels right and Deployments, Services, and network policies all line up. Get them wrong and a Service will point at nothing.
Example
# Show labels on all Pods
kubectl get pods --show-labels
# Filter Pods by a label
kubectl get pods -l app=web
# Set-based selection
kubectl get pods -l 'environment in (staging,production)'
# Add or change a label on the fly
kubectl label pod web-abc123 tier=frontendWhen to use it
- A team labels pods with environment=production and uses a label selector in a Service to route traffic only to production pods, not staging ones.
- An SRE uses kubectl get pods -l app=api,version=v2 to quickly filter and list only the pods belonging to the v2 canary release.
- A Deployment's selector uses matchLabels to ensure it owns only pods it created, preventing unintended adoption of orphaned pods.
More examples
Add and filter by labels
Adds two labels to a pod imperatively, then filters the pod list using single and multi-label selectors.
kubectl label pod my-pod env=production tier=backend
# Filter by a single label
kubectl get pods -l env=production
# Filter by multiple labels
kubectl get pods -l env=production,tier=backendmatchLabels in Deployment selector
Shows a Deployment selector that matches on two labels, ensuring it owns only pods with both app=api and version=v2.
spec:
selector:
matchLabels:
app: api
version: v2
template:
metadata:
labels:
app: api
version: v2Set-based selector in a Job
Uses set-based matchExpressions for more expressive selector logic: env in {staging, production} AND tier not cache.
selector:
matchExpressions:
- key: env
operator: In
values: [staging, production]
- key: tier
operator: NotIn
values: [cache]
Discussion