What is the need of defining .spec.selectors in Kubernetes Deployment.yaml file?

10/19/2021

The .spec.selector field defines how the Deployment finds which Pods to manage. But we also defines labels inside template then what is the extra things we are getting with .spec.selectors field because Deployment can find the Pods to be managed with the label defined in template also ?

In the below code how can the pod with "label occloud.oracle.com/open-network-policy: allow" is managed by deployment as it is not described in spec.selectors

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cheeseshop
spec:
  replicas: 1
  progressDeadlineSeconds: 180
  selector:
     matchLabels:
       app.kubernetes.io/name: tutorial
       app.kubernetes.io/component: cheeseshop
  template:
     metadata:
       labels:
         app.kubernetes.io/name: tutorial
         app.kubernetes.io/component: cheeseshop
         occloud.oracle.com/open-network-policy: allow
       name: cheeseshop
   
-- Pulkit Sharma
google-kubernetes-engine
kubernetes
kubernetes-deployment
kubernetes-pod
yaml

1 Answer

10/19/2021

spec.seletor field is used by Deployment/Replicaset controllers. It must be a subset of the labels specified in the podTemplate. That is why you may have additional labels in your pods. But they will still be managed by the deployment.

spec.selector is also used to check is any existing ReplicaSet already matched these conditions. If the Deployment controller found an orphan ReplicaSet, it will be used by the deployment instead of creating a new one. See https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/deployment/deployment_controller.go#L222

-- Arnaud Develay
Source: StackOverflow