Sign In

Curriculum 11: Labels, Selectors & Annotations

Applying Labels

12 min · 15 XP

Applying Labels

Labels are key-value pairs attached to Kubernetes objects. They are the primary mechanism for organizing, selecting, and filtering resources across your cluster.

Adding Labels Imperatively

Use kubectl label to add labels to existing resources:

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

# Add a label to a deployment
kubectl label deployment api-server team=backend

# Add labels to all pods matching a selector
kubectl label pods -l app=web tier=frontend

Adding Labels in YAML

Labels are defined in the metadata.labels section of any resource:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: payment-service
  labels:
    app: payment
    team: billing
    environment: production
spec:
  replicas: 3
  selector:
    matchLabels:
      app: payment
  template:
    metadata:
      labels:
        app: payment
        team: billing
        version: v2.1.0
    spec:
      containers:
        - name: payment
          image: payment-service:2.1.0

Notice that labels appear in multiple places -- on the Deployment itself, in the selector, and on the Pod template.

Updating and Removing Labels

# Overwrite an existing label (requires --overwrite)
kubectl label pod my-app environment=staging --overwrite

# Remove a label by appending a minus sign
kubectl label pod my-app environment-

Naming Conventions

Kubernetes enforces rules on label keys and values:

  • Keys can have an optional prefix (DNS subdomain, max 253 characters) followed by a slash and a name (max 63 characters). Example: app.kubernetes.io/name
  • Values must be 63 characters or fewer, and contain only alphanumerics, hyphens, underscores, and dots

The Kubernetes community recommends these standard labels:

LabelExample Value
app.kubernetes.io/namemysql
app.kubernetes.io/version5.7.21
app.kubernetes.io/componentdatabase
app.kubernetes.io/part-ofwordpress
app.kubernetes.io/managed-byhelm

Key Takeaways

  • Labels are key-value pairs for organizing and selecting resources
  • Use kubectl label to add, update, or remove labels imperatively
  • Define labels in metadata.labels for declarative management
  • Follow the app.kubernetes.io/ convention for standard labels
  • Always use --overwrite when changing an existing label value