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:
1 2 3 4 |
metadata: labels: <key1>: <value1> <key2>: <value2> |
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:
1 2 3 4 5 6 7 8 9 10 11 |
apiVersion: v1 kind: Pod metadata: name: huongdanjava labels: env: test purpose: blog spec: containers: - name: node-hello image: gcr.io/google-samples/node-hello:1.0 |
Check the result after creating new Pod from the above .yaml spec file, you will see the following result:
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:
1 2 3 |
selector: <key1>: <value1> ... |
If you want to use Selector for Node then you can define:
1 2 3 |
nodeSelector: <key1>: <value1> ... |
Set-based requirements use the in, notin and exists operators to filter only the Label’s key.
1 2 3 4 5 |
selector: matchLabels: <key1>: <value1> matchExpressions: - { key: <key2>, operator: In, values: [<value1, <value2>]} |
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.