I am new to Kubernetes, so this might be obvious, but in a deployment yaml, why do we have to define the labels in the deployment metadata, then define the same labels in the template metadata, but match those separately in the selector?
Shouldn't it be obvious that the template belongs to the deployment it's under? Is there a use case for a deployment to have a template it doesn't match?
apiVersion: apps/v1
kind: Deployment
metadata:
name: <b>api-backend</b>
spec:
replicas: 2
selector:
matchLabels:
app: <b>api-backend</b>
template:
metadata:
labels:
app: <b>api-backend</b>
spec:
#...etc
I might be missing some key understanding of k8s or yamls.
Having the template with no label, and it seems to work, but I don't understand why. Kubernetes could be auto-magically inserting the labels.
CodePudding user response:
Technically, the parameter matchLabels
decides on which Pods belongs to the given Deployment (and the underlying ReplicaSet). In practice, I have never seen a Deployment with different labels
than matchLabels
. So, the reason might be the uniformity between other Kubernetes resources (like Service where the matchLabels
makes more sense).
I recommend reading the blog post matchLabels, labels, and selectors explained in detail, for beginners.
CodePudding user response:
Let's simplify labels, selectors and template labels first.
- The Labels in the metadata section are assigned to the deployment itself.
- The Labels in the
.spec.template
section are assigned to the pods created by the deployment. These are actually called PodTemplate labels. - The selectors provide uniqueness to your resource. It is used to identify the resources that match the labels in
.spec.selector.matchLabels
section.
Now, it is not mandatory to have all the podTemplate Labels in the matchLabels section. a pod can have many labels but only one of the matchLabels is enough to identify the pods. Here's an use case to understand why it has to be used
"Let’s say you have deployment X which creates two pods with label nginx-pods
and image nginx
and another deployment Y which applies to the pods with the same label nginx-pods
but uses images nginx:alpine
. If deployment X is running and you run deployment Y after, it will not create new pods, but instead, it will replace the existing pods with nginx:alpine
image. Both deployment will identify the pods as the labels in the pods matches the labels in both of the deployments .spec.selector.matchLabels
"
CodePudding user response:
Because the Deployment.metadata.labels belongs to the Deployment resource, and the Deployment.spec.template.metadata.labels to the Pods which are handled by the Deployment controller. The Deployment controller knows which Pods are belongs to which Deployment based on the labels on the Pod resources.
This is why you have to specify the labels this way.