In Kubernetes, node affinity (Node Affinity) can be used to specify the association rules between Pods and nodes to determine which nodes the Pods should be scheduled on.
-
Node affinity type:
requiredDuringSchedulingIgnoredDuringExecution
: Pod must meet the node affinity rules, otherwise it cannot be scheduled.preferredDuringSchedulingIgnoredDuringExecution
: Pods are more inclined to meet node affinity rules, but are not required to do so.
-
Use node affinity in the Pod's YAML file:
- In the Pod's YAML file, use
affinity
fields to specify node affinity rules. - In
affinity
fields, usenodeAffinity
subfields to define node affinity rules.
- In the Pod's YAML file, use
Here's an example showing how to use node affinity in a Pod's YAML file:
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: nginx:latest
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: env
operator: In
values:
- production
In the above example, nodeAffinity
the field defines a required node affinity rule, that is, the Pod needs to be scheduled env=production
on the node with the label.
Note that node affinity rules can use other operators ( NotIn
, Exists
, DoesNotExist
etc.) and multiple match expressions to define more complex rules.
Using node affinity, pods can be scheduled to specific nodes based on the node's labels and conditions to meet the needs of the application or to take advantage of resources or environments on specific nodes.