Labels are the mechanism used to organize Kubernetes objects. A label is a key-value pair with certain restrictions concerning length and allowed values but without any pre-defined meaning. You're free to choose labels as you see fit, for example, to express environments such as "this pod is running in production" or ownership, like "department X owns that pod".
Let's create a pod that initially has one label (
kubectl apply -f https://raw.githubusercontent.com/openshift-evangelists/kbe/main/specs/labels/pod.yaml
The get subcommand can be used to display a pod's labels:
kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS labelex 1/1 Running 0 6s env=development
You can add a label to the pod through the `label` subcommand:
kubectl label pods labelex owner=jay
Running the `get` subcommand from above shows the new label in addition to the existing one:
NAME READY STATUS RESTARTS AGE LABELS labelex 1/1 Running 0 65s env=development,owner=jay
kubectl get pods --selector owner=michael
--selectoroption can be abbreviated to
-l, so selecting pods that are labelled with
env=developmentcan also be done using:
kubectl get pods -l env=development
kubectl apply -f https://raw.githubusercontent.com/openshift-evangelists/kbe/main/specs/labels/anotherpod.yaml
kubectl get pods -l 'env in (production, development)'
Since we have each pod has one of those two labels, they both appear in the output:
NAME READY STATUS RESTARTS AGE labelex 1/1 Running 0 6m39s labelexother 1/1 Running 0 46s
Other verbs also support label selection. For example, you could remove both of these pods with the same selector:
kubectl delete pods -l 'env in (production, development)'
kubectl delete pods labelex kubectl delete pods labelexother