Labels, Selectors and Annotations
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
- Labels are key/value pairs that are attached to objects, such as pods
- Labels are intended to be used to specify identifying attributes of objects that are meaningful and relevant to users.
- Ability to group kubernetes objects together and filter them based on needs is achieved using labels and selectors.
- 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.