How to use labels and selectors?
· Category: Kubernetes
Short answer
Labels are key-value pairs attached to Kubernetes objects. Selectors use these labels to filter and match resources, enabling Services, Deployments, and network policies to target specific Pods.
Steps
- Add labels in metadata.
- Use
matchLabelsormatchExpressionsin selectors. - Query resources with
kubectl get pods -l key=value.
Example
metadata:
labels:
app: web
tier: frontend
env: production
Selector:
selector:
matchLabels:
app: web
matchExpressions:
- key: tier
operator: In
values:
- frontend
CLI:
kubectl get pods -l app=web
kubectl get pods -l 'tier in (frontend, backend)'
Tips
- Use a consistent labeling convention across teams.
- Labels are mutable; annotations are better for metadata that should not be queried.
- Avoid putting sensitive data in labels.
Common issues
- Typos in label keys cause selectors to match nothing.
matchExpressionsis more flexible but more verbose thanmatchLabels.- Label values have length and character restrictions.