Why we need labels ?

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.

How to see Pod labels

  • Lets run nginx app Pod
$ kubectl run webserver --image=nginx --restart=Never

See the labels of a Pods

$ kubectl get pods --show-labels

Add a custom label to Pod

  • We can add label to Pod using kubectl label command. shell $ kubectl label pod webserver app=frontend

Here we have add a label app=frontend to pod webserver.

Use label selectors

-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
  • Lets see how can I select the Pods with label app=frontend.
$ kubectl get pods --selector=app=frontend

Remove labels

  • See the labels of webserver

    $ kubectl get pods --show-labels
    
  • Remove the app label

    $ kubectl label pod webserver app-
    

How to get labels of deployments

$ kubectl get deploy --show-labels

Lets talk about Node Selector

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.

Create a pod using Node selector

apiVersion: v1
kind: Pod
metadata:
  name: gpu-demo
  labels:
    env: test
spec:
  containers:
  - name: gpu-demo
    image: nginx:1.9.1
  nodeSelector:
    type: gpu

Deploy the pod

$ kubectl apply -f gpudemo.yaml

Check the status of the pod

$ 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

Lets check the label of nodes and label it as type:gpu

$ kubectl get nodes --show-labels
$ kubectl label nodes <YOUR_NODE_NAME> type:gpu

Lets check the status of the pending pod

$ kubectl get po

Now you will see the pod is scheduled on the same node where where you set the label

Matchlabels and MatchExpressions

  • Lets create two pods
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

List the pods with labels

$ kubectl get pods --show-labels

Lets find out pods based on equality

$ kubectl get pods -l environment=production, tier=frontend 
$ kubectl get pods -l environment!=production,tier!=frontend

Lets play with Set based requirement

$ kubectl get pods -l 'environment in (testing),tier in (backend)'

Set Based Requirement can implement negative matching via exists operator.

$  kubectl get pods -l 'environment notin (uat)'