Pages

Sunday, May 13, 2018

Kubernetes - Labels

Labels are a mechanism that we use to organize objects in kubernetes. A Kubernetes object  can be anything from containers ,pods to services. Label is a key-value pair that we can attach to a resource for identification.

Label contain identifying information and are used by the selector queries or within selector
section in object definitions. Lets create a pod with basic labels and see how it works,

To create a basic label for a pod we can use the manifest file as below,
[root@manja17-I13330 kube-testing]# cat basic-label-pod.yml
apiVersion: v1
kind: Pod
metadata:
 name: testing-service
 labels:
   env: dev
spec:
 containers:
   - name: test-ser
     image: docker.io/jagadesh1982/testing-service
     ports:
     - containerPort: 9876

From the above config we are actually creating a pod with label “env=dev”.

To see the label available for a pod we can use the command,
[root@manja17-I13330 kube-testing]# kubectl get pods --show-labels
NAME                READY     STATUS RESTARTS   AGE LABELS
sample-test-c9lcw      1/1 Running     0 1d  app=sample-test,version=2
testing-service           1/1 Running  0 50s env=dev

If we want to assign a label while a pod is running, we can use
[root@manja17-I13330 kube-testing]# kubectl label pod testing-service owner=kube
pod "testing-service" labeled

[root@manja17-I13330 kube-testing]# kubectl get pods --show-labels
NAME                       READY STATUS RESTARTS   AGE LABELS
sample-test-c9lcw    1/1 Running    0 1d     app=sample-test,version=2
testing-service         1/1 Running   0 1m   env=dev,owner=kube

Selector in kubernetes allow to use labels for filtering , for example to list pods that have an owner is equal to kube

[root@manja17-I13330 kube-testing]# kubectl get pods --selector owner=kube
NAME               READY STATUS RESTARTS   AGE
testing-service   1/1 Running  0 2m

The --selector option can be abbreviated to -l, so to select pods that are labelled with env=dev,

[root@manja17-I13330 kube-testing]# kubectl get pods -l env=dev
NAME                 READY STATUS RESTARTS   AGE
testing-service   1/1 Running   0 2m


To get all pods that are labelled with dev or test
[root@manja17-I13330 kube-testing]# kubectl get pods -l 'env in (dev,test)'
NAME                  READY STATUS RESTARTS   AGE
testing-service   1/1 Running   0 3m

More to Come, Happy Learning :-)

No comments :

Post a Comment