Script Valley
Kubernetes: From Containers to Clusters
Containers and the Kubernetes FoundationLesson 1.5

Kubernetes labels and selectors: how resources find each other

label definition, label selectors, equality-based selectors, set-based selectors, annotations vs labels, practical labeling strategy, kubectl label command

Labels Are Key-Value Metadata

Kubernetes labels and selectors diagram

Labels are arbitrary key-value pairs attached to Kubernetes objects. They have no meaning to Kubernetes itself — you define what they mean. Their power comes from selectors: other resources use selectors to find and operate on labeled objects.

Services route traffic to Pods matching a selector. Deployments manage Pods matching a selector. ReplicaSets scale Pods matching a selector. Labels are the glue holding Kubernetes resources together.

Adding and Querying Labels

# Add a label to a running pod
kubectl label pod my-pod environment=production

# Query pods by label
kubectl get pods -l app=frontend
kubectl get pods -l environment=production,app=frontend

# Set-based selector (in, notin, exists)
kubectl get pods -l 'environment in (staging, production)'

# Remove a label (trailing dash)
kubectl label pod my-pod environment-

Labels vs Annotations

Labels are for selecting and grouping — keep them short and structured. Annotations are for non-identifying metadata: build timestamps, contact info, tool-specific config. You cannot use annotations in selectors.

metadata:
  labels:
    app: frontend
    version: "2.1"
    environment: production
  annotations:
    deployed-by: "github-actions"
    last-commit: "a3f9b12"