Sign In

Curriculum 11: Labels, Selectors & Annotations

Filtering with Selectors

15 min · 15 XP

Filtering with Selectors

Label selectors let you query and filter Kubernetes resources based on their labels. They power everything from kubectl get filtering to how Services find their Pods.

The -l Flag

Use -l (or --selector) to filter resources by label:

# Find all pods with a specific label
kubectl get pods -l app=nginx

# Find pods across all namespaces
kubectl get pods -l environment=production -A

# Delete all pods with a label
kubectl delete pods -l tier=test

Equality-Based Selectors

Equality-based selectors match exact label values using =, ==, and !=:

# Match pods where environment equals production
kubectl get pods -l environment=production

# Match pods where environment does NOT equal production
kubectl get pods -l environment!=production

# Combine multiple conditions (AND logic)
kubectl get pods -l app=web,environment=staging

Multiple selectors separated by commas are combined with AND -- all conditions must be true.

Set-Based Selectors

Set-based selectors use in, notin, and exists for more flexible matching:

# Match pods in either staging or production
kubectl get pods -l 'environment in (staging, production)'

# Match pods NOT in the test environment
kubectl get pods -l 'environment notin (test, dev)'

# Match pods that HAVE a "release" label (any value)
kubectl get pods -l 'release'

# Match pods that do NOT have a "canary" label
kubectl get pods -l '!canary'

Note the single quotes around set-based expressions to prevent shell interpretation.

Selectors in YAML

Deployments and Services use matchLabels and matchExpressions in their specs:

selector:
  matchLabels:
    app: web
  matchExpressions:
    - key: environment
      operator: In
      values:
        - staging
        - production

The matchLabels field uses equality-based matching. The matchExpressions field supports set-based operators: In, NotIn, Exists, and DoesNotExist.

Key Takeaways

  • Use -l to filter any kubectl get, describe, or delete command
  • Equality selectors use = and != for exact matching
  • Set-based selectors use in, notin, and existence checks
  • Comma-separated selectors combine with AND logic
  • Services and Deployments use matchLabels and matchExpressions in YAML