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

  1. Add labels in metadata.
  2. Use matchLabels or matchExpressions in selectors.
  3. 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.
  • matchExpressions is more flexible but more verbose than matchLabels.
  • Label values have length and character restrictions.