Browse topics

Labels and selectors

Version
1.37
Review
Draft

Summary#

Labels are key and value pairs attached to objects. Selectors pick objects by those labels, and controllers and Services use them to find Pods. Commas in a selector mean that every requirement must match.

Syntax#

sh
kubectl get pods -l 'app=shop,tier!=backend'
kubectl get pods -l 'tier in (frontend,backend),!canary'
kubectl label pod NAME track=stable --overwrite
kubectl label pod NAME track-
yaml
selector:
  matchLabels:
    app: shop
  matchExpressions:
    - {key: tier, operator: In, values: [frontend, backend]}

Example#

Selection reads only metadata, so the example does not wait for the Pods to start.

sh
(
  set -eu
  ns="ref-labels-$$"
  kubectl create namespace "$ns" >/dev/null
  trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
  kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null

  image=registry.k8s.io/pause:3.10
  kubectl run -n "$ns" web-stable --image="$image" --labels=app=shop,tier=frontend,track=stable >/dev/null
  kubectl run -n "$ns" web-canary --image="$image" --labels=app=shop,tier=frontend,track=canary >/dev/null
  kubectl run -n "$ns" api --image="$image" --labels=app=shop,tier=backend >/dev/null
  kubectl run -n "$ns" db --image="$image" --labels=app=shop,tier=data >/dev/null

  echo "tier=frontend"
  kubectl get -n "$ns" pods -l tier=frontend -o name --sort-by=.metadata.name
  echo "set-based, not canary"
  kubectl get -n "$ns" pods -l 'tier in (frontend,backend),track!=canary' -o name --sort-by=.metadata.name

  kubectl label -n "$ns" pod web-canary track=stable --overwrite
  echo "track=stable"
  kubectl get -n "$ns" pods --selector track=stable -o name --sort-by=.metadata.name
)

Expected output#

Text
tier=frontend
pod/web-canary
pod/web-stable
set-based, not canary
pod/api
pod/web-stable
pod/web-canary labeled
track=stable
pod/web-canary
pod/web-stable

Common mistakes#

track!=canary also matches objects that have no track label, which is why pod/api appears. Add track as a second requirement to demand the key. Quote selectors that contain spaces, parentheses or ! so the shell passes them unchanged. There is no OR operator between requirements; use in for several values of one key.

Version applicability#

The example targets Kubernetes 1.37. matchExpressions is supported by resources such as Deployments, DaemonSets and Jobs. A Service selector is a plain map and supports only equality.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0