Labels, Selectors and Annotations

Hitesh Pattanayak
2 min readApr 14, 2022
credits: https://theithollow.com/

With capabilities of deploying numerous amount of objects (pods, services, ingress, deployments, jobs, replicasets, etc) and ability to orchestrate them, here comes a challenge of organising them, connecting them, etc.

Labels, Selectors and Annotations concepts in k8s come to our rescue.

Labels & Selectors

  1. Labels are key/value pairs that are attached to objects, such as pods
  2. Labels are intended to be used to specify identifying attributes of objects that are meaningful and relevant to users.
  3. Ability to group kubernetes objects together and filter them based on needs is achieved using labels and selectors.
  4. Selectors help us filter kubernetes objects based on the attached properties (labels).

When we create pods, we attach some labels.

And then when we create service to redirect requests to the pods, we create selectors and matchLabels to link service and pods

An example of a pod with labels is as below (here app: mock-app and function: backend are the labels):

apiVersion: v1
kind: Pod
metadata:
name: simple-webapp
labels:
app: mock-app
function: backend
spec:
containers:
- name: simple-webapp
image: simple-webapp
ports:
- containerPort: 8080

After creating a pod with certain labels, we can filter it by:

kubectl get pods --selector app=mock-app

An example of a service using selector to attach itself to pods (here app: mock-app and function: backend under spec/selector are the selectors)

apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
app: mock-app
function: backend
ports:
- protocol: TCP
port: 80
targetPort: 9376

Having one selector is enough unless further nested filtering is required.

Annotations are used to record other details for informatory purposes. For details like build information, name or contact.

--

--

Hitesh Pattanayak

Senior Product Engineer @ Infracloud Technologies | 7 years of experience | Polyglot | Backend Developer | Kubernetes and AWS practitioner | Finance Enthusiast