π·οΈ Kubernetes Labels & Selectors
Labels are key-value pairs attached to Kubernetes objects like Pods, Services, and ReplicaSets. They are used for grouping, selecting, and organizing resources.
β Why Use Labels?
- Identify objects by environment, app, version, or team
- Target resources for management and monitoring
- Connect Services, ReplicaSets, and Deployments to Pods
π·οΈ Add Labels to Resources
At creation:
kubectl run nginx --image=nginx --labels="tier=frontend,env=prod"
To an existing object:
kubectl label pod nginx-pod app=nginx tier=frontend
Overwrite existing label:
kubectl label pod nginx-pod env=staging --overwrite
π View Labels
On resources:
kubectl get pods --show-labels
kubectl get pod nginx-pod --show-labels
Filter by label:
kubectl get pods -l app=nginx
kubectl get svc -l tier=frontend
Multiple label filters:
kubectl get pods -l 'app=nginx,tier=frontend'
β Remove a Label
kubectl label pod nginx-pod env-
The
-afterenvmeans "remove this label"
π§ Label Best Practices
- Use consistent keys:
env,app,tier,version - Use hyphens, not underscores:
app-name, notapp_name - Avoid spaces in values
Examples:
labels:
app: web
env: prod
tier: frontend
π― Match Labels with Selectors
ReplicaSet Selector:
selector:
matchLabels:
app: nginx
Service Selector:
selector:
tier: frontend
If labels donβt match the selector, the resource wonβt link or control the Pod.
π¦ Annotations vs. Labels
| Feature | Labels | Annotations |
|---|---|---|
| Purpose | Selectors, grouping | Metadata not used for selection |
| Size limit | Small (short values) | Can be long, unstructured text |
| Use case | App ID, version, tier | Git commit info, debug links |
Example Annotation:
metadata:
annotations:
git-sha: "78f2a9d"
β Summary
- Labels organize and target resources
- Selectors connect controllers and services to Pods
- Use
kubectl label,kubectl get -l, andkubectl describefor label management - Combine with
matchLabelsin YAML to ensure resource alignment - Use annotations for metadata that doesnβt affect selection