Working with Labels and Selectors
1. Adding Labels to Resources
| Command | Action |
kubectl label pod web env=prod | Add label |
kubectl label pods --all tier=frontend | Bulk add |
kubectl label -f file.yaml owner=team | Label from file |
| Recommended Labels | Purpose |
app.kubernetes.io/name | App name |
app.kubernetes.io/instance | Instance identifier |
app.kubernetes.io/version | App version |
app.kubernetes.io/component | Role: frontend, db, etc. |
app.kubernetes.io/part-of | Higher-level app |
app.kubernetes.io/managed-by | Tool: Helm, Argo, Kustomize |
2. Viewing Resource Labels
kubectl get pods --show-labels
kubectl get pods -L app -L env # selected labels as columns
kubectl get pod web -o jsonpath='{.metadata.labels}'
| Flag | Effect |
--show-labels | All labels in last column |
-L key | Specific label as own column |
3. Filtering by Label Selectors
kubectl get pods -l app=web
kubectl get pods -l 'env in (prod,staging)'
kubectl get pods -l 'tier=frontend,!canary'
| Operator | Syntax |
| = | key=value |
| != | key!=value |
| in | 'key in (a,b)' |
| notin | 'key notin (a)' |
| exists | 'key' |
| not exists | '!key' |
4. Using Equality-Based Selectors
| Where | Form |
| Services | spec.selector: {app: web} (eq only) |
| ReplicationController | spec.selector: {app: web} (eq only) |
| kubectl -l | Supports eq and set-based |
5. Using Set-Based Selectors
selector:
matchExpressions:
- { key: env, operator: In, values: [prod, staging] }
- { key: canary, operator: DoesNotExist }
| Operator | Use |
| In | Value in list |
| NotIn | Value not in list |
| Exists | Key present |
| DoesNotExist | Key absent |
6. Removing Labels
kubectl label pod web env-
kubectl label pods --all tier-
| Syntax | Meaning |
key- | Trailing dash removes the label |
7. Overwriting Labels
| Command | Effect |
kubectl label pod web env=staging --overwrite | Replace value |
8. Using Labels in YAML
metadata:
labels:
app.kubernetes.io/name: web
app.kubernetes.io/version: "1.4.2"
env: prod
| Constraint | Value |
| Key prefix | Optional DNS subdomain ≤253 chars |
| Key name | ≤63 chars, alphanumeric, -, _, . |
| Value | ≤63 chars, alphanumeric, -, _, . (or empty) |
9. Selecting with matchLabels
selector:
matchLabels: { app: web, env: prod }
| Property | Detail |
| Format | {key:value} map, all conditions AND |
| Immutable | For Deployment/StatefulSet after creation |
10. Selecting with matchExpressions
selector:
matchLabels: { app: web }
matchExpressions:
- { key: tier, operator: In, values: [frontend, edge] }
- { key: deprecated, operator: DoesNotExist }
Note: matchLabels and matchExpressions are AND-combined.