Labels in Kubernetes

Labels

As our application grows in size and complexity, so the Kubernetes cluster. We might be adding/removing new services, setting up staging/test environments, etc. That means, we may have to introduce a new set of deployments, service objects to support new services, and a group of objects in a cluster to support a new environment for staging/test, etc. The flexibility of this scale is achieved through Labels.

Labels are key/value pairs assigned to Kubernetes objects. Kubernetes objects can have multiple labels. Labels enable the logical grouping of objects.

image.png

Creation of Labels

Labels are specified in YAML definition of Kubernetes objects:

apiVersion: v1
kind: Pod
metadata:
  name: mango
  labels:
    env: staging
    app: mango
    ver: 1
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 80

We can also set labels through implicit command as follows:

kubectl run mango --image=nginx --labels="ver=1,app=mango,env=staging"

To list the labels:

kubectl get pod --show-labels

image.png

Label Selectors

Using label selectors Kubernetes allows to group objects with a combination of labels. Kubernetes allows two types of selectors: equality-based and set-based. In equality-based selectors, multiple labels can be specified with commas as separators and they are assumed to be combined with logical AND (&&) operator.

apiVersion: v1
kind: Pod
metadata:
  name: mango
spec:
  containers:
    - name: mango
      image: "nginx"
  selector:
    matchLabels: 
        app: mango
        matchExpressions:
            - {key: ver, operator: In, values: [1,2]}

Set-based label selectors allow combining objects from the given set of labels.

environment in (production, qa) // Environment haveing either of given values
tier notin (frontend, backend) // Value of tier not present in given values
partition // Key with name partition is present
!partition // Key with name partition is not present

Following implicit command retrieves all pods with label ver=1:

image.png

The power of labels will be evident as we explore Kubernetes further.