Junior — Middle
How can you ensure placement of two containers in Kubernetes so that they do not end up on the same physical node?
sobes.tech AI
Answer from AI
To ensure that two containers are not placed on the same physical node in Kubernetes, you can use Pod Anti-Affinity. This rule allows you to specify that pods with certain labels should not be on the same node.
Example manifest with anti-affinity:
apiVersion: v1
kind: Pod
metadata:
name: example-pod
labels:
app: myapp
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- myapp
topologyKey: kubernetes.io/hostname
containers:
- name: container1
image: myimage1
Here, topologyKey: kubernetes.io/hostname means that pods with the label app: myapp will not be placed on the same host (node). Thus, if you have two pods with this label, Kubernetes will try to place them on different nodes.
If you have two containers in the same pod, they will always be on the same node, as the pod is the minimal deployment unit. To separate containers onto different nodes, you need to run them in different pods with anti-affinity.