Learn about Label and Selector in Kubernetes

Labels are key:value pairs assigned to an object in Kubernetes such as Pod, which is used so that we can identify a Kubernetes object quickly. And Selector is used to filtering a set of Kubernetes objects that satisfy certain conditions. How is it in details? Let’s find out more in this tutorial!

The first thing is that we can define the Label in the spec file that defines the information of a Kubernetes object.

Label syntax is as follows:

In which key1:value1, key2:value2 are the value pairs that we want to assign to the Kubernetes object.

For example, if I want to run a Pod with the Label assigned to this Pod, I will define the spec of Pod as follows:

Check the result after creating new Pod from the above .yaml spec file, you will see the following result:

Learn about Label and Selector in Kubernetes

As you can see, my Pod huongdanjava has been assigned with 2 Labels that we defined in the spec file.

We can have multiple Kubernetes objects with the same Label, to facilitate filtering a set of Kubenetes objects having the same Label or satisfies one or several criteria, the Selector concept is also used in Kubernetes.

Separated by commas, the criteria for Selector’s filter are defined with an AND clause. We have two ways to filter with Selector:

  • Equality-based requirements
  • Set-based requirements,

Equality-based requirements will use the =, ==,! = operators to allow us to filter using the key and value of Label. We define this Selector in the spec file as follows:

If you want to use Selector for Node then you can define:

Set-based requirements use the in, notin and exists operators to filter only the Label’s key.

We can use Selector to create Pods on the Nodes that the Label of these Nodes meet a certain condition or create Deployment using Pods whose Label satisfies a certain condition.

Add Comment