Join the DZone community and get the full member experience.
Join For Free
This article describes how to configure your Pods to run in specific nodes based on affinity and anti-affinity rules. Affinity and anti-affinity allow you to inform the Kubernetes Scheduler whether to assign or not assign your Pods, which can help optimize performance, reliability, and compliance.
There are two types of affinity and anti-affinity, as per the Kubernetes documentation:
Let's see a couple of scenarios where you can use this configuration.
In this scenario, I'm running a Kafka cluster with 3 nodes (Pods). For resilience and high availability, I want to have each Kafka node running in a different worker node.
In the configuration above, I'm using because it allows us to create rules based on labels on Pods and not only in the node itself. In addition to that, I'm setting the because I don't want two Kafka Pods running in the same cluster at any time. The field look for the label in the Pod and is the label node. Pod anti-affinity requires nodes to be consistently labeled, in other words, every node in the cluster must have an appropriate label matching .
In the event of a failure in one of the workers (considering that we only have three workers), the Kafka Pod will be in a status because the other two nodes already have a Kafka node running.
Conceptually, node affinity is similar to where you define where a Pod will run. However, affinity gives us more flexibility. Let's say that in our cluster we have two worker nodes with GPU processors and some of our applications must run in one of these nodes.
In this scenario, the Data Science applications will be assigned to workers 1 and 2. Worker 3 will never host a Data Science application.
Affinity and anti-affinity rules provide us flexibility and control on where to run our applications in Kubernetes. It's an important feature to create a highly available and resilient platform. There are more features, like , that you can study in the official Kubernetes documentation.