Goglides Dev 🌱

Balkrishna Pandey
Balkrishna Pandey

Posted on

matchLabels, labels, and selectors in deployment

Labels are key-value pairs that can be attached to Kubernetes objects. Labels can be used to organize and group objects, and they can be used to select objects for operations such as deletion and updates.

Selectors are used to select a group of objects for an operation. Selectors can be specified using labels, and they can be used to select all objects with a given label or all objects that match a certain pattern.

Kubernetes deployment uses Labels and Selectors to select which pods need to be updated when a new version of a pod is deployed.

Let's take a look at how this works with an example.

Match Labels, Selectors, Deployment

In the above deployment.yaml file,

  • line number 5-6 is labels assigned to deployment objects. It assigns a label to the deployment itself. You can do operations based on these labels, for example, If you want to delete the deployment, you can use kubectl delete deployment -l app=nginx. If you want to list that deployment you can use kubectl get deployment -l app=nginx

  • line 10-12 is a selector which is looking for pods with labels app=nginx and tier=frontend. So, if there aren’t any pods with those labels when the deployment is first created, the deployment will do nothing. But, if there are, then the deployment will manage those pods. So, that’s basically what a selector does. It’s a way for the deployment to find the pods that it’s responsible for.

  • line 17-18 is labels assigned to the pod object. The second metadata describes the pod that the deployment will create. So, it gives labels to the actual pod objects that get created by the deployment.

This deployment object will create 2 replicas of pods with labels app=nginx as shown below,


kubectl get pods  --show-labels

Enter fullscreen mode Exit fullscreen mode

Output:


NAME           READY  STATUS  RESTARTS  AGE  LABELS

nginx-85658cc69f-f5ffm  1/1   Running  0     6s  app=nginx,pod-template-hash=85658cc69f

nginx-85658cc69f-vpbmd  1/1   Running  0     6s  app=nginx,pod-template-hash=85658cc69f

Enter fullscreen mode Exit fullscreen mode

Top comments (0)