Search code examples
kubernetesaffinity

Is it a good practice (feasible) to combine both nodeAfinity and podAffinity rules when assigning Pods to Nodes on kubernetes


Is it a good practice (feasible) to combine both nodeAfinity and podAffinity rules when assigning Pods to Nodes on kubernetes.

Example :

apiVersion: v1
kind: Pod
metadata:
  name: node-and-pod-affinity-combined
spec:
  affinity:
    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/e2e-az-name
            operator: In
            values:
            - e2e-az1
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: node-label-key
            operator: In
            values:
            - some-node-label-value

Solution

  • Sure you can combine them. Actually this enforces a sort of affinity on scheduling of pods you have selected using podAffinity. Even if those pods do not have any nodeAffinity or podAffinity themselves, scheduler will try to schedule them to nodes on which your node-and-pod-affinity-combined pods are running.

    More common use case would be using nodeAffinity and podAntiAffinity together to spread the pods on set of nodes.