WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kubernetes · Intermediate · question 29 of 100

Explain the concept of affinity and anti-affinity rules in Kubernetes.?

📕 Buy this interview preparation book: 100 Kubernetes questions & answers — PDF + EPUB for $5

In Kubernetes, affinity and anti-affinity rules are used to specify the relationship between Pods and the nodes they are scheduled on. Affinity rules specify that Pods should be scheduled on nodes that match certain criteria, while anti-affinity rules specify that Pods should not be scheduled on nodes that match certain criteria.

Affinity rules and anti-affinity rules are defined using labels and selectors in the Pod specification. Here is an example of a Pod specification with an affinity rule:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: my-image
  nodeSelector:
    disktype: ssd

In this example, the nodeSelector field is used to specify an affinity rule that requires the Pod to be scheduled on a node with the label disktype=ssd. This ensures that the Pod is scheduled on a node with a solid-state drive (SSD) instead of a traditional hard disk drive (HDD).

Here is an example of a Pod specification with an anti-affinity rule:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: my-image
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: app
            operator: In
            values:
            - my-app
        topologyKey: kubernetes.io/hostname

In this example, the affinity field is used to specify an anti-affinity rule that requires the Pod to not be scheduled on a node that already has a Pod with the label app=my-app. The topologyKey field is used to specify that the rule should be enforced at the hostname level.

    

Affinity and anti-affinity rules can be used to achieve a variety of scheduling goals, such as ensuring that Pods are scheduled on nodes with certain resources, distributing Pods across multiple availability zones or regions, or preventing Pods from being scheduled on nodes that already have other Pods running. By using these rules, Kubernetes can provide a flexible and powerful scheduling system that can be tailored to the specific needs of each application or workload.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kubernetes interview — then scores it.
📞 Practice Kubernetes — free 15 min
📕 Buy this interview preparation book: 100 Kubernetes questions & answers — PDF + EPUB for $5

All 100 Kubernetes questions · All topics