Use Labels to Organize and Select Resources
In this step, you'll learn how to use labels in Kubernetes to organize and select resources efficiently. Labels are key-value pairs that help you manage and organize Kubernetes objects.
First, verify the current labels on your pods:
kubectl get pods --show-labels
Example output:
NAME READY STATUS RESTARTS AGE LABELS
nginx-deployment-xxx-yyy 1/1 Running 0 30m app=nginx,pod-template-hash=xxx
nginx-deployment-xxx-zzz 1/1 Running 0 30m app=nginx,pod-template-hash=yyy
nginx-deployment-xxx-www 1/1 Running 0 30m app=nginx,pod-template-hash=zzz
Select pods using specific labels:
kubectl get pods -l app=nginx
Example output:
NAME READY STATUS RESTARTS AGE
nginx-deployment-xxx-yyy 1/1 Running 0 30m
nginx-deployment-xxx-zzz 1/1 Running 0 30m
nginx-deployment-xxx-www 1/1 Running 0 30m
Let's add a custom label to one of the pods:
kubectl label pods nginx-deployment-xxx-yyy environment=development
Replace nginx-deployment-xxx-yyy
with the name of one of your pods.
Example output:
pod/nginx-deployment-xxx-yyy labeled
Now, select pods with multiple label selectors:
kubectl get pods -l app=nginx,environment=development
Example output:
NAME READY STATUS RESTARTS AGE
nginx-deployment-xxx-yyy 1/1 Running 0 30m
Remove a label from a pod:
kubectl label pods nginx-deployment-xxx-yyy environment-
Example output:
pod/nginx-deployment-xxx-yyy unlabeled
Demonstrate label selection in services:
kubectl describe service nginx-clusterip-service
Look for the "Selector" section, which shows how services use labels to identify pods.
Key points about labels:
- Labels are key-value pairs attached to Kubernetes objects
- Used for organizing, selecting, and filtering resources
- Can be added, modified, or removed dynamically
- Services and deployments use labels to manage related pods