In Kubernetes, Pod affinity (Pod Affinity) can be used to define the association rules between Pod and other Pods to control their scheduling on the same or different nodes.
-
Pod affinity type:
requiredDuringSchedulingIgnoredDuringExecution
: The Pod must meet the affinity rules, otherwise it cannot be scheduled.preferredDuringSchedulingIgnoredDuringExecution
: Pods are more inclined to meet affinity rules, but are not required to do so.
-
Use Pod affinity in the Pod's YAML file:
- In the Pod's YAML file,
affinity
specify Pod affinity rules using fields. - In
affinity
fields, usepodAffinity
orpodAntiAffinity
subfields to define Pod affinity rules.
- In the Pod's YAML file,
Here's an example showing how to use Pod affinity in a Pod's YAML file:
apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: nginx:latest
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- frontend
topologyKey: kubernetes.io/hostname
In the above example, podAffinity
the field defines a required Pod affinity rule, that is, the Pod needs to be scheduled on the same app=frontend
node as other Pods with labels, and kubernetes.io/hostname
the topology labels are used for matching.
Note that Pod affinity rules can use other operators ( NotIn
, Exists
, DoesNotExist
etc.) and multiple match expressions to define more complex rules.
Pod affinity can be used to control the association between pods and other pods when scheduling pods to meet requirements such as deployment strategies, data locality, or load balancing.