Skip to content

🏷️ Kubernetes Labels & Selectors

Labels are key-value pairs attached to Kubernetes objects like Pods, Services, and ReplicaSets. They are used for grouping, selecting, and organizing resources.


βœ… Why Use Labels?

  • Identify objects by environment, app, version, or team
  • Target resources for management and monitoring
  • Connect Services, ReplicaSets, and Deployments to Pods

🏷️ Add Labels to Resources

At creation:

kubectl run nginx --image=nginx --labels="tier=frontend,env=prod"

To an existing object:

kubectl label pod nginx-pod app=nginx tier=frontend

Overwrite existing label:

kubectl label pod nginx-pod env=staging --overwrite

πŸ” View Labels

On resources:

kubectl get pods --show-labels
kubectl get pod nginx-pod --show-labels

Filter by label:

kubectl get pods -l app=nginx
kubectl get svc -l tier=frontend

Multiple label filters:

kubectl get pods -l 'app=nginx,tier=frontend'

❌ Remove a Label

kubectl label pod nginx-pod env-

The - after env means "remove this label"


🧠 Label Best Practices

  • Use consistent keys: env, app, tier, version
  • Use hyphens, not underscores: app-name, not app_name
  • Avoid spaces in values

Examples:

labels:
  app: web
  env: prod
  tier: frontend

🎯 Match Labels with Selectors

ReplicaSet Selector:

selector:
  matchLabels:
    app: nginx

Service Selector:

selector:
  tier: frontend

If labels don’t match the selector, the resource won’t link or control the Pod.


πŸ“¦ Annotations vs. Labels

Feature Labels Annotations
Purpose Selectors, grouping Metadata not used for selection
Size limit Small (short values) Can be long, unstructured text
Use case App ID, version, tier Git commit info, debug links

Example Annotation:

metadata:
  annotations:
    git-sha: "78f2a9d"

βœ… Summary

  • Labels organize and target resources
  • Selectors connect controllers and services to Pods
  • Use kubectl label, kubectl get -l, and kubectl describe for label management
  • Combine with matchLabels in YAML to ensure resource alignment
  • Use annotations for metadata that doesn’t affect selection