'Can I define multiple nodes in nodeAffinity with a priority or a "weight"?

I have a kubernetes pod and 4 nodes in my cluster. I would like to schedule that pod to node-2 first if it's available and then node-4, node-3 and last priority to node-1. Assuming that node-x is the built in kubernetes.io/hostname value, is there any way to possibly define a priority for these 4 nodes inside a nodeAffinity?

This is what I've tried:

    nodeAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
        nodeSelectorTerms:
        - matchExpressions:
          - key: kubernetes.io/hostname
            operator: In
            values:
            - node-2
            - node-4
            - node-3
            - node-1

However, the pod seems to always go to node-1.



Solution 1:[1]

This seems to be working:

nodeAffinity:
  requiredDuringSchedulingIgnoredDuringExecution:
    nodeSelectorTerms:
    - matchExpressions:
      - key: node-type
        operator: In
        values:
        # a common label applied to all nodes
        - node-label
  preferredDuringSchedulingIgnoredDuringExecution:
  - weight: 100
    preference:
      matchExpressions:
      - key: kubernetes.io/hostname
        operator: In
        values:
        - node-2
  - weight: 50
    preference:
      matchExpressions:
      - key: kubernetes.io/hostname
        operator: In
        values:
        - node-4
  - weight: 20
    preference:
      matchExpressions:
      - key: kubernetes.io/hostname
        operator: In
        values:
        - node-3
.
.
and so on

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aayush Pathak