Labels are a key/value formatted peice of metadata attached to an object within Kubernetes. Labels provide additional information about the object with relevance to the consumer or object. For example, a label can specify hardware characteristics of a node or if a workload is for testing of production.
Labels implicitly group like objects together while providing a lookup mechanism for users, controllers and external systems.
For this example, I have a deployment for a web service which runs on internal infrastructure and one which runs on DMZ infrastructure.
The labels run=nginx and either location=dmz or location=internal are on the pods at deployment. An object can have multiple labels, but an object cannot have multiple labels with the same key. If an objects manifest has multiple label entries with the same key, the last value is applied.
The below code block shows the pods deployed by applying the above deployment manifests.
NOTE: The deployment controller automatically applies the pod-template-hash label.
Adding one or more --selector options to kubectl get pods filters the pods returned.
Use multiple selectors to get internal nginx pods.
The deployment controller uses a selector to identify which pods are part of a deployment. Creating a deployment also creates a replicaSet object which is monitored by the replication controller to ensure that the number of pods running matches the desired number.
Right now our deployments have 4 pods running in a ready state.
Running kubectl get rs -o yaml displays the configuration of a replicaSet
Lets adust one of the labels used on a pod, so it no longer matches our selector.matchLabels spec and see what happens.
The replica controller could only find 3 pods running using the matchLabel selector after we changing the run label on pod web-internal-6b444b6dd9-kd8w2 and deployed another pod to remediate the issue.
Labels and selectors have many additional uses to the one covered in this post; they are a core part of the Kubernetes platform.