Open In App

How To Use Kubernetes Labels and Selectors?

Last Updated : 16 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Kubernetes (also known as K8s) is an open-source Container Management tool. It helps us automate all the processes like deployment, load balancing, rolling update, etc. We can basically deploy, scale, and manage containerized applications.

In Kubernetes, labels and selectors provide a flexible and effective approach to facilitate selection for managing resources like restart/delete/etc. operations, and also for human readability. They are mentioned in the configuration file i.e., yaml files for deployments. They are used to connect services with a pod.

A briefer understanding of Labels and Selectors could be as follows:

Labels are key-value pairs that are used to identify K8s resources like deployments, pods, services. They are completely user-defined, may be tailored to meet our particular needs, and are used to identify and classify resources.

Selectors are utilized to find and categorize resources according to their labels. They can be used to specify criteria for choosing resources that correspond to particular label combinations. They also help in specifying the set of resources to be targeted or managed in the Kubernetes components, including services, deployments, replica sets, and stateful sets.

Prerequisite: Kubernetes Deployments, Kubernetes – Labels & Selectors

Using Labels and Selectors

To use labels and selectors in our applications, we need to specify them in the yaml file.

First of all, for adding labels we could add something like this:

“metadata”:
{
“labels”:
{
“app” : “demo-app”,
“env” : “uat”,
“branch”: “${CI_COMMIT_BRANCH}”
“release”: “1.2.2”
}
}

In the above, we added four labels to the specific replica set in the deployment. We can add as many labels as we want depending on our use case and how we choose to visualize it on the dashboard and select it via selectors. We can have many meaningful labels like version, some Gitlab default variables, etc.

The complete deployment/manifest yaml example can be viewed in the image below:

manifest-yaml

Here, we apply the yaml to create the resource – in this case Deployment. Since we have added labels to this deployment, we can view the pods with the labels and also view pods by specifying the labels we want by these commands:

kubectl get pods –show-labels

kubectl get pods -l app=demo-app

Origin-Server-(1)-(2)

Based on the labels we add, we can then add selectors to filter the resources.

For example, we can have the following selectors to select one particular pod:

“selector”:
{
“app” : “demo_app”,
“env” : “uat”,
“pod-template-hash”: “3478fsh”
}

We can select the deployments/resources we want to view with the selectors using a kubectl command:

kubectl get pods –selector=”env=uat”

We can have two types of selectors:

  1. Equality-based – As the name suggests is based on operators – “=”, “!=” and “==” which represent equality or inequality. This will help filter the resources. Example -> env=uat
  2. Set-based – These are based on operators – “in”,”not in” and “exists” which will represent present/ not-present in the set. Example -> env in (uat).
  3. Wildcard – These can help in wildcard selection of the pods and we could select multiple resources with this. Wildcard characters used are * and ?. * would mean any number of characters could be present.

Advantages of using Labels and Selectors:

As mentioned earlier labels and selectors are used to select and filter the resources in Kubernetes, but this also has many added advantages. Some of them include:

  • Bulk Operations: Performing bulk operations on the K8s resources like pods or deployments becomes very easy with labels and selectors. For example, we want to shut down/ delete all the deployments deployed from the branch “demo” we can just use a command with selectors like this:

kubectl delete deployments -l ‘branch = demo’

  • Ownership: Knowing ownership is also one of the good use cases of labels and selectors. We can add labels to our services/deployments with predefined Gitlab variables which give us useful information about the branch, commit SHA, version, etc. This can be used to define ownership within the application based on the branch/version.
  • Grouping Resources: This advantage is similar to filtering but the use case could be different. Suppose, pods in one of environments is down and we want to group and find what the issue is and perform operations on them to resolve the same – labels and selectors makes it much easier to do.

kubectl get pods -l ‘env=uat’

  • Human Readability: This might be noticed much but is also a very useful advantage of having labels and selectors. If we have meaningful labels which convey all the essential things required for a resource, it becomes much easier for the developer and also for a new person to understand the resource.
  • Scheduling: We can also schedule pods based on some labels and selecting them through selectors. By making Kubernetes schedule particular deployments onto particular nodes, we have greater control over the resources by utilizing labels.
  • Automatically scaling: Using labels and selectors, we can also automatically scale up/down the pods based on the needs. This can be possible through nodeSelectors. These selectors can help provide a node selection constraint
    manifest-yaml-(1)
  • Route Traffic: We can also route traffic to pods with the help of labels and selectors. Routing is handled usually by the Ingress resource. So, we can specify the same selectors in our Deployment and Service and eventually use it in the Ingress to route to those particular paths.
  • Monitor health: For monitoring health of pods, we will have to use probes like startup/liveness/readiness along with labels and selectors. We can add labels and selectors to services that we want to monitor and then add probes to them. Now, the probes will run periodically and we can also use our selectors to check the health of all of them at once.

Good Practices

  • Make the best use of labels by applying all the Recommended Labels. Recommended Labels are a set of standard labels list provided by Kubernetes to fully utilize it. All of them describe a unique thing about the application. Some of them are:

app.kubernetes.io/name: demo_app

app.kubernetes.io/instance: exception-fix-2

app.kubernetes.io/version: “1.2.2”

app.kubernetes.io/component: mongodb

app.kubernetes.io/managed-by: kubernetes

  • We should avoid changing the labels multiple times without some valid reason. This can also lead to unwanted results like the crashing of pods since their labels change or reverse.
  • We should always manage labels with code and not directly command line. Even though it is easier to just use the kubectl command to create/delete/update labels, it should be done through code so that it is maintained properly.
  • We should try to avoid conflicts in the naming of labels by adding some prefix/suffix so that it is recognized easily.
  • Never store sensitive data in labels. Labels are not encrypted and thus should not be used to store private data – because if anyone gets access to the cluster can see all the labels & selectors.
  • We should also use a convention for labels. This helps us in avoiding conflict between labels. The convention could be like this – <prefix>/<name>. Prefix could be a domain or higher level app and the name could be the specific name.

Conclusion

Labels and selectors are very useful if utilized properly. By using labels, we can maintain our resources very efficiently. They also act as metadata in Kubernetes which gives useful insights about the data (application). This can be quite valuable for people working with the system, as demonstrated by features like human-readable annotations, as it helps them navigate the resources and gives them a sense of how everything fits together.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads