Kubernetes Affinity
?? Saral Saxena ??????
?11K+ Followers | Linkedin Top Voice || Associate Director || 15+ Years in Java, Microservices, Kafka, Spring Boot, Cloud Technologies (AWS, GCP) | Agile , K8s ,DevOps & CI/CD Expert
Kubernetes affinity rules step into the spotlight, offering a sophisticated mechanism for influencing how pods are distributed across a cluster.?
Kubernetes affinity is about setting rules that dictate how pods are placed relative to nodes and other pods. These rules allow users to influence the scheduling decisions of the Kubernetes scheduler, ensuring that pods are deployed on the most appropriate nodes based on various criteria, such as hardware requirements, software needs, or even geographical location. Affinity can be broadly categorized into two types: Node Affinity and Pod Affinity/Anti-Affinity
Node Affinity:
Node Affinity is the successor to the simpler?nodeSelector?feature, offering a more expressive syntax that allows for more nuanced selection logic. It specifies constraints or preferences that affect how pods are placed relative to nodes. These constraints can be "hard" (required) or "soft" (preferred), providing a balance between strict requirements and desirable attributes.
Pod Affinity and Anti-Affinity
While Node Affinity focuses on the relationship between pods and nodes, Pod Affinity and Anti-Affinity govern how pods are placed relative to one another. These rules can be used to ensure that certain pods are co-located in the same node, zone, or region, or to keep them separated for redundancy and fault tolerance.
Affinity rules are essential for optimizing applications for various scenarios:
Implementing Node and Pod Affinity requires defining rules in your pod specifications. Here’s a brief look at how you can specify Node and Pod Affinity:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: "hardware-type"
operator: In
values:
- GPU
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: "disk-type"
operator: In
values:
- ssd
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: "app"
operator: In
values:
- webserver
topologyKey: "kubernetes.io/hostname"
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: "app"
operator: In
values:
- database
topologyKey: "kubernetes.io/hostname"