<p>I am trying to create a podAffinity for the replicas of my deployment to be deployed in different nodes within my GCP cluster, I have followed the documentation an this site <a href="https://thenewstack.io/implement-node-and-pod-affinity-anti-affinity-in-kubernetes-a-practical-example/" rel="nofollow noreferrer">https://thenewstack.io/implement-node-and-pod-affinity-anti-affinity-in-kubernetes-a-practical-example/</a> but I get this error when executing apply:</p>
<pre><code>error: error validating &quot;.\\K8s\\6flask-deployment.yaml&quot;: error validating data: ValidationError(Deployment.spec.template.spec.affinity.podAntiAffinity.requiredDuringSchedulingIgnoredDuringExecution[0].labelSelector): unknown field &quot;MatchExpressions&quot; in io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector;
</code></pre>
<p>This is my flask-deployment.yaml. I have tried to set it also underneath the first spec but it does not work neither</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: flask-deployment
  namespace: flask-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: flask-app
      deploy: separate
      run: together
  template:
    metadata:
      labels:
        app: flask-app
        deploy: separate
        run: together
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              MatchExpressions:
                - key: deploy
                  operator: In
                  values:
                  - separate
            topologyKey: kubernetes.io/hostname  
      containers:
</code></pre>
<p>Is it an identation mistake? the kubernetes linter does not flag anything and I have been comparing with other examples here in SO and over the web and I cannot find the mistake</p>

<p>Whatever key-value you specify in <code>matchExpressions</code> also needs to be in <code>labels</code> and <code>matchLabels</code> of the pod <code>spec</code> instead of <code>metadata</code> section.It should be as below</p>
<pre><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongodb-deployment
  namespace: flask-app
spec:
  replicas: 2  
  selector:
    matchLabels:
      deploy: separate
  template:
    metadata:
      labels:
        deploy: separate
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: deploy
                operator: In
                values:
                - separate
            topologyKey: &quot;kubernetes.io/hostname&quot;
</code></pre>
