Kubernetes Labels

Guide to Kubernetes Autoscaling
calendar April 13, 2022
Chapter 11 Kubernetes Labels

Kubernetes (K8s) labels are key-value pairs that can be a powerful resource for managing, configuring, and troubleshooting. Users can use Kubernetes labels to add meaningful metadata to any Kubernetes object or resource. Because of their extensibility, a sound understanding of Kubernetes labels can make you a better K8s administrator and improve your container workflows.

In this article, we take a closer look at labels and the selectors used to filter them and work through example commands and use cases so you can get hands-on experience with K8s labels.

The basics: Kubernetes labels and selectors

K8s selectors allow users to filter objects based on labels, and can be used by the Kubernetes platform as well. From a user perspective, K8s labels and selectors can manipulate objects such as:

  • Pods
  • Nodes
  • Services
  • Secrets
  • Ingress Resources
  • Deployments
  • Namespaces

Why do we need to use Kubernetes labels?

While you can use K8s without labels, the metadata they provide is valuable to humans working with the platform. Users often need Kubernetes labels to identify K8s objects and perform useful operations on them.

For example, consider a set of pods like the example below running on the Kubernetes cluster.

6 discrete K8s pods.
6 discrete K8s pods.

Let’s assume we need to delete all the pods that belong to the dev environment. Without assigning labels, there’s no easy way to tell which pods fit that description. As a result, it can become difficult and time-consuming to find each pod and delete it.

Now, let’s suppose we assign a label to each pod based on the environment it belongs to. Here the environment is either dev or prod for example.

K8s pods with Kubernetes labels indicating their environment.
K8s pods with Kubernetes labels indicating their environment.

Now, using the label with key-value pair env: dev we can use the K8s selector with the kubectl delete command to quickly delete all the pods that belong to the dev environment.

3 K8s pods with the env: dev label.
3 K8s pods with the env: dev label.

In addition to pod deletion, we could perform many other operations on those pods. For example, we can list pods, list pods and namespaces together, or direct traffic to a list of pods or service or endpoints.

Machine learning for Kubernetes sizing

Learn More
Visualize Utilization Metrics Set Resource Requests & Limits Set Requests & Limits with Machine Learning Identify mis-sized containers at a glance & automate resizing Get Optimal Node Configuration Recommendations
Kubernetes
Kubernetes + Densify

Kubernetes labels syntax and naming

When working with Kubernetes labels, there are restrictions concerning the length and allowed values. Specifically, a valid label value:

  • must be 63 characters or less (can be empty),
  • unless empty, must begin and end with an alphanumeric character ([a-z0-9A-Z]),
  • can only contain dashes (-), underscores (_), dots (.), and alphanumerics

For example, the following pod manifest has two valid labels, environment: production and app: nginx

apiVersion: v1
kind: Pod
metadata:
  name: label-demo
  labels:
    environment: production
    app: nginx
  spec:
    containers:
    - name: nginx
      image: nginx:1.14.2
      ports:
      - containerPort: 80                    

How to manage Kubernetes labels?

K8s labels can be defined when a new object is created or attached to existing objects and modified later. A user can edit the object YAML definition manually or use kubectl to create/update labels.

Let’s create a pod with the label env=develop

$ cat pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: labelex
  labels:
    env: develop
spec:
  containers:
  - name: sise
    image: quay.io/openshiftlabs/simpleservice:0.4.0
    ports:
    - containerPort: 9870
                    
$kubectl apply -f pod.yaml
                    
pod/labelex created                                      

After pod creation, we can see the label using the get subcommand. The Kubernetes labels are displayed as an additional column in the output:

$ kubectl get pods --show-labels

NAME      READY   STATUS    RESTARTS   AGE   LABELS
labelex   1/1     Running   0          71s   env=develop                                                            

Next, we can use the label subcommand to add another label to the pod.

$ kubectl label pods labelex owner=ijaz

pod/labelex labeled                                                        

Now, we can use the --overwrite flag to change the value for the existing label key.

$ kubectl label pods labelex owner=ahmad --overwrite

pod/labelex labeled                                                        

Identify under/over-provisioned K8s resources and use Terraform to auto-optimize

WATCH 3-MIN VIDEO

Next, check if the new label is attached using the get command, the output will show the new label in addition to the existing ones.

$ kubectl get pods --show-labels

NAME      READY   STATUS    RESTARTS   AGE     LABELS
labelex   1/1     Running   0          9m32s   env=development,owner=ahmad                                                            

To list the pods with label key “owner” and value “ahmad”, we will use the --selector option.

$ kubectl get pods --selector owner=ahmad

NAME      READY   STATUS    RESTARTS   AGE
labelex   1/1     Running   0          16m                                                        

Next, use the short option -l to select the pod with label env=develop.

$ kubectl get pods -l env=develop

NAME      READY   STATUS    RESTARTS   AGE
labelex   1/1     Running   0          18m                                                        

Kubernetes also supports set-based selectors. To demonstrate this, let’s create another pod with env=prod and owner=ijaz

$ cat prod-pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: labelexother
  labels:
    env: prod
    owner: ijaz
spec:
  containers:
  - name: sise
    image: quay.io/openshiftlabs/simpleservice:0.4.0
    ports:
    - containerPort: 9870
                    
$ kubectl apply -f prod.pod.yaml                                                        

We can now list the pods where the environment is either develop or prod by using the set-based selector. For example:

$ kubectl get pods -l 'env in (prod, develop)'

NAME           READY   STATUS    RESTARTS   AGE
labelex        1/1     Running   0          26m
labelexother   1/1     Running   0          26s                                                        

Other actions also support label selection. For example, we can delete both the pods using this command:

$ kubectl delete pods -l 'env in (prod, develop)'

pod "labelex" deleted
pod "labelexother" deleted                                                        

Kubernetes labels are not only for pods. You can apply them to all sorts of objects, including nodes, services, and deployments.

Learn the “80-20 rule” applied to Kubernetes optimization

Watch Free Video

Kubernetes labels example use cases

Now that we’ve covered the basics of working with K8s labels, let’s take a look at some common use cases.

Services and Deployments

The most common use case for labels is using label selectors in Kubernetes services and deployment objects. A service object targets pods based on label selectors.

For example, consider this service definition:

apiVersion: v1
kind: Service
metadata:
  name: app-service
spec:
  selector:
    app: MyApp
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9370                                                        

The above specification will create a new service object named "app-service", targeting TCP port 9370 on any pod with the app=MyApp label.

Similarly, using Kubernetes labels and label selectors in deployment objects enables the deployment to find the pods to be managed under the deployment.

Consider the following deployment spec:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80                                                        

The .spec.selector field defines how the deployment should find which Pods to manage. In this case, you select a label defined in the Pod template (app: nginx).

Using Labels in Advance Scheduling

Using labels and selectors is also common in advanced Kubernetes scheduling. Examples of advanced K8s scheduling include node selector and pod affinity.

If you need to place a pod on a specific node, you can label the node and then use the label in your pod deployment manifest. For example, you can use this command to label a node with SSD storage.


$ kubectl label nodes kubernetes-foo-node-1.c.a-robinson.internal disktype=ssd.                                    

Then, in the deployment specification, you can use the label disktype=ssd as node selector to place the pod on the node with label disktype=ssd.

apiVersion: v1
  kind: Pod
  metadata:
    name: nginx
    labels:
      env: test
  spec:
    containers:
    - name: nginx
      image: nginx
      imagePullPolicy: IfNotPresent
    nodeSelector:
      disktype: ssd                                                        

Kubernetes labels best practices

While Kubernetes labels are customizable, it is best practice to use certain standard labels. For example, from the K8s docs, recommended labels include:

Key Description Example
name The name of the application Nginx
instance A unique name identifying the instance of an application frontend-blue
version The current version of the application 1.0.0
component The component within the architecture Database

Free Proof of Concept implementation if you run more than 5,000 containers

Request PoC

Some other common labels are:

Key Description Example
environment The environment in reference to the systems development lifecycle staging
owner The team or individual responsible for deploying or maintaining the application component “Ijaz Khan”
managed-by The tool being used to manage the operation of an application helm
business-unit The business unit that owns this application “finance”

Conclusion

Using Labels and Selectors in Kubernetes are not only useful constructs required in many operations, but also, are part of Kubernetes best practices, they make the operations on Kubernetes objects simple and easier. Labels are also used internally by Kubernetes for the same purpose. Users need to follow the best practices of using label names that are relevant to the application stack and environment as described in this article.

You like our article?

Follow our LinkedIn monthly digest to receive more free educational content like this.

Follow LinkedIn K8s digest

Discover the benefits of optimized cloud & container resources. Try Densify today!

Request a Demo