Multiple ways to select pods using labels in Kubernetes
- k8s
- kubernetes
- howto
Show all the labels of the running pods
#You can use the following command to see the labels of the running pods.
kubectl get po --show-labels
You will see the following output, showing all the pods and their labels.
NAME READY STATUS RESTARTS AGE LABELS
blue-backend 1/1 Running 0 2m59s color=blue,tier=backend
green-frontend 1/1 Running 0 2m59s color=green,tier=frontend
red-backend 1/1 Running 0 2m59s color=red,tier=backend
red-frontend 1/1 Running 0 2m59s color=red,tier=frontend
Get the pods with specific labels and display them as columns
#Just like in the previous example, you can use the following command - notice flag -L
and pass the labels which you want to see as columns.
kubectl get pods -L color,tier
You will see in the output that label color
and tier
are displayed as columns.
NAME READY STATUS RESTARTS AGE COLOR TIER
blue-backend 1/1 Running 0 3m7s blue backend
green-frontend 1/1 Running 0 3m7s green frontend
red-backend 1/1 Running 0 3m7s red backend
red-frontend 1/1 Running 0 3m7s red frontend
Get the pods without a specific label
#Equally easily, you can get all the pods without a specific label.
kubectl get pods -L color,tier -l '!color'
Because there are no pods without color
label, you will see the following output.
No resources found in default namespace.
Get the pods where label has a specific value
#In this example, we are looking for running pods with label color
with value red
.
kubectl get pods -L color,tier -l 'color=red'
You will see that only pods with color=red
are displayed.
NAME READY STATUS RESTARTS AGE COLOR TIER
red-backend 1/1 Running 0 4m32s red backend
red-frontend 1/1 Running 0 4m32s red frontend
Get the pods where the value of label is one of the specified values
#Here, we are looking for running pods with label color
with value blue
or green
. The command is
kubectl get pods -L color,tier -l 'color in (blue,green)'
You will see that only pods with color=blue
or color=green
are displayed.
NAME READY STATUS RESTARTS AGE COLOR TIER
blue-backend 1/1 Running 0 5m blue backend
green-frontend 1/1 Running 0 5m green frontend