Senior
How to spread containers of the same pod across different nodes?
sobes.tech AI
Answer from AI
In Kubernetes, containers within the same pod are by default launched on the same node, since a pod is the smallest deployment unit. To distribute containers across different nodes, they need to be run in different pods.
If the goal is to ensure that pods with certain containers do not end up on the same node, the following mechanisms are used:
- Anti-affinity — rules that prohibit placing pods with certain labels on the same node.
- Node affinity — rules that specify preferences or requirements for nodes.
Example of anti-affinity in a pod manifest:
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- myapp
topologyKey: "kubernetes.io/hostname"
This rule prohibits placing pods with the label app: myapp on the same node.
Thus, to distribute containers, you need to:
- Run them in separate pods.
- Configure anti-affinity so that pods do not land on the same node.