Sobes.tech
Middle+

What are affinity and anti-affinity in Kubernetes?

sobes.tech AI

Answer from AI

Affinity and anti-affinity in Kubernetes are mechanisms that allow managing pod placement on cluster nodes based on certain rules and preferences.

  • Affinity sets rules for pods to be placed near other pods or on nodes with specific labels. This helps, for example, to group related services to reduce latency.

  • Anti-affinity, on the other hand, makes pods avoid being placed near certain other pods or on nodes with specific labels. This is useful for increasing fault tolerance, so that copies of the same service are not on the same node.

Example of using affinity in a Pod manifest:

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

Here, the pod will be placed on a node where there is already a pod with the label app=frontend.

What are affinity and anti-affinity in Kubernetes… - sobes.tech