<p>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?</p>
<p>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?</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-backend
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api-backend
  template:
    metadata:
      labels:
        app: api-backend
    spec:
      #...etc
</code></pre>
<p>I might be missing some key understanding of k8s or yamls.</p>
<p>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.</p>

<p>Technically, the parameter <code>matchLabels</code> decides on which Pods belongs to the given Deployment (and the underlying ReplicaSet). In practice, I have never seen a Deployment with different <code>labels</code> than <code>matchLabels</code>. So, the reason might be the uniformity between other Kubernetes resources (like Service where the <code>matchLabels</code> makes more sense).</p>
<p>I recommend reading the blog post <a href="https://medium.com/@zwhitchcox/matchlabels-labels-and-selectors-explained-in-detail-for-beginners-d421bdd05362" rel="nofollow noreferrer">matchLabels, labels, and selectors explained in detail, for beginners</a>.</p>
