Kubernetes Label Selector And Field Selector

Ashutosh Kumar
MayaData
Published in
2 min readJul 14, 2018

The resources that we create in a kubernetes cluster can be organised by using labels. Before we talk about field selector in Kubernetes, let us walk through quickly about labels.

Labels are key value pairs that can be used to identify, or group the resources in Kubernetes. In other words, labels can be used to select resources from a list.
You can label Kubernetes native resources as well as Custom Resources. To understand it more clearly, let us do some hands on practice on labels.

The tutorial will assume that you have a working minikube setup or a Kubernetes cluster setup.

Following is link to the yaml . It’s application will create a pod.

https://raw.githubusercontent.com/sonasingh46/artifacts/master/samples/sample-pod.yaml

The yaml looks following:

apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
env: development
spec:
containers:
- name: label-example
image: sonasingh46/node-web-app:latest
ports:
- containerPort: 8000

Notice the bold text in above yaml. That is one way to add labels to a resource by specifying in yaml.
Let us create a pod by executing following command:

kubectl apply -f https://raw.githubusercontent.com/sonasingh46/artifacts/master/samples/sample-pod.yaml

You can use above command directly or copy the content to save it on your local machine in a file , say sample-pod.yaml.

ashutosh@miracle:~/Desktop/artifacts/samples$ kubectl apply -f sample-pod.yaml 
pod/example-pod created
ashutosh@miracle:~/Desktop/artifacts/samples$ kubectl get po
NAME READY STATUS RESTARTS AGE
example-pod 1/1 Running 0 3m

Now, let us run the following commands to check for labels in the pod.

ashutosh@miracle:~/Desktop/artifacts/samples$ kubectl get pod example-pod --show-labelsNAME                      READY     STATUS    RESTARTS   AGE     LABELSexample-pod               1/1       Running   0          3m        env=development

As you can see in the above output example-pod is having a label of key value pair as env=development .
You can also do a kubectl get pod example-pod -o yaml to see all the fields along with labels.

Let us add another label to the above pod…

Read the complete article in MayaData’s Blog

--

--