For multiple reasons, there can be a need to run a pod on a specific worker node.
Node affinity is a set of rules used by the scheduler to determine where a pod can be placed.
In Kubernetes terms, it is known as
nodeSelector
, and nodeAffinity/podAffinity
fields under PodSpec
.In Kubernetes, we can achieve nodeAffinity with the help of:
nodeSelector
nodeAffinity
(more flexibility)
Node affinity is conceptually similar to
nodeSelector
– it allows you to constrain which nodes your pod is eligible to be scheduled on, based on labels on the node.We can label our nodes using key-value pairs and use these labels to schedule a pod on a given node. Node selectors have limitations. We can only use a single label and selector to select a pod. We cannot use complex logic to decide which node should be used for scheduling a pod. Example: we cannot specify a pod to be scheduled on a node with
compute: high
or compute:medium
at the same time. For such use cases, we need Node Affinity. Select a node for a pod
Example: schedule the pod on a node with high compute power.
kubectl label node node01 compute=high
apiVersion: v1 kind: Pod metadata: name: web-pod spec: nodeSelector: compute: high containers: - name: nginx image: nginx
Commands
- Label a node -
kubectl label node <node-name> <key>=<value>
- View labels of a node -
k describe node <node-name>