Working with Labels and Selectors

1. Adding Labels to Resources

CommandAction
kubectl label pod web env=prodAdd label
kubectl label pods --all tier=frontendBulk add
kubectl label -f file.yaml owner=teamLabel from file
Recommended LabelsPurpose
app.kubernetes.io/nameApp name
app.kubernetes.io/instanceInstance identifier
app.kubernetes.io/versionApp version
app.kubernetes.io/componentRole: frontend, db, etc.
app.kubernetes.io/part-ofHigher-level app
app.kubernetes.io/managed-byTool: 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}'
FlagEffect
--show-labelsAll labels in last column
-L keySpecific 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'
OperatorSyntax
=key=value
!=key!=value
in'key in (a,b)'
notin'key notin (a)'
exists'key'
not exists'!key'

4. Using Equality-Based Selectors

WhereForm
Servicesspec.selector: {app: web} (eq only)
ReplicationControllerspec.selector: {app: web} (eq only)
kubectl -lSupports eq and set-based

5. Using Set-Based Selectors

selector:
  matchExpressions:
  - { key: env, operator: In, values: [prod, staging] }
  - { key: canary, operator: DoesNotExist }
OperatorUse
InValue in list
NotInValue not in list
ExistsKey present
DoesNotExistKey absent

6. Removing Labels

kubectl label pod web env-
kubectl label pods --all tier-
SyntaxMeaning
key-Trailing dash removes the label

7. Overwriting Labels

CommandEffect
kubectl label pod web env=staging --overwriteReplace value

8. Using Labels in YAML

metadata:
  labels:
    app.kubernetes.io/name: web
    app.kubernetes.io/version: "1.4.2"
    env: prod
ConstraintValue
Key prefixOptional 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 }
PropertyDetail
Format{key:value} map, all conditions AND
ImmutableFor 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.