In kubernetes , label is a key value pair and it provides ‘identifying metadata’ for objects. These are fundamental qualities of objects that will be used for grouping , viewing and operating.
$ kubectl run webserver --image=nginx --restart=Never
$ kubectl get pods --show-labels
kubectl label
command.
shell
$ kubectl label pod webserver app=frontend
Here we have add a label app=frontend
to pod webserver
.
-Lets start another webserver pod with name webserver-2.
$ kubectl run webserver-2 --image=nginx --restart=Never
Now we have two Pods.
$ kubectl get pods --show-labels
$ kubectl get pods --selector=app=frontend
See the labels of webserver
$ kubectl get pods --show-labels
Remove the app
label
$ kubectl label pod webserver app-
$ kubectl get deploy --show-labels
You might have a mix of nodes say you have few GPU nodes and rest are just t2.micro. Now you would like to run a specific pod on a GPU instance machine. Lets see how you can do that.
apiVersion: v1
kind: Pod
metadata:
name: gpu-demo
labels:
env: test
spec:
containers:
- name: gpu-demo
image: nginx:1.9.1
nodeSelector:
type: gpu
$ kubectl apply -f gpudemo.yaml
$ kubectl get po
You will see the pod is in pending state as it will not able to schedule as long it find the node type:gpu
$ kubectl get nodes --show-labels
$ kubectl label nodes <YOUR_NODE_NAME> type:gpu
$ kubectl get po
Now you will see the pod is scheduled on the same node where where you set the label
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
name: prod-pod
labels:
environment: production
tier: frontend
spec:
containers:
- name: prod
image: nginx:alpine
ports:
- containerPort: 80
---
apiVersion: v1
kind: Pod
metadata:
name: test-pod
labels:
environment: testing
tier: backend
spec:
containers:
- name: test
image: nginx:alpine
ports:
- containerPort: 80
EOF
$ kubectl get pods --show-labels
$ kubectl get pods -l environment=production, tier=frontend
$ kubectl get pods -l environment!=production,tier!=frontend
$ kubectl get pods -l 'environment in (testing),tier in (backend)'
$ kubectl get pods -l 'environment notin (uat)'