What is pod affinity in Kubernetes?
Pod affinity in Kubernetes is a concept that allows you to influence the scheduling of pods in such a way that they are placed on nodes with other pods that have a specified label or set of labels. It helps in improving the performance and efficiency of your applications by co-locating related pods on the same node.
There are two types of pod affinity:
- Node Affinity: This type of affinity ensures that pods are scheduled to nodes with specific labels. You can specify node affinity rules based on node labels, and pods that match these rules are more likely to be scheduled on nodes that meet the specified criteria. Example of node affinity YAML:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: <label-key>
operator: In
values:
- <label-value>
- Pod Affinity: This type of affinity ensures that a pod is scheduled to nodes with other pods that have certain labels. It allows you to specify affinity rules at the pod level, and pods are scheduled close to other pods that satisfy these rules. Example of pod affinity YAML:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: <label-key>
operator: In
values:
- <label-value>
topologyKey: <node-label-key>
In both cases, the affinity rules can be either “requiredDuringSchedulingIgnoredDuringExecution” (hard affinity) or “preferredDuringSchedulingIgnoredDuringExecution” (soft affinity). Hard affinity means that the rules must be satisfied for the pod to be scheduled, while soft affinity allows some flexibility.
Pod affinity is useful in scenarios where certain pods benefit from being close to each other for performance reasons or to facilitate communication. For example, you might want to schedule pods of a database and its corresponding application on the same node to minimize latency and maximize throughput.
Reference: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/