Kubernetes Pod Affinity and Pod Anti Affinity Tutorial

Kubernetes Pod Affinity and Pod Anti Affinity Tutorial

We use Pod Affinity rules to schedule pods on some node by matching specified condition in more expressive methods. Pod affinity/anti-affinity allows you to create/don’t create new pods on the nodes based on the labels on other pods in that node.

Kubernetes Pod Affinity:

Pod affinity tells the scheduler to locate a new pod on the node, which has the running pod with particular labels.

Kubernetes Pod anti affinity:

Pod anti affinity will prevent the scheduler to locate a new pod on the node, which has the running pod with particular labels.

There are two types of pod affinity rules: required and preferred.

Required: Required rules must be met before a pod can be scheduled on a node.

preferred: the scheduler will try to enforce but will not guarantee. it will try to schedule the pods on matched condition nodes. if its is not finds the node then it will randomly select the nodes and it will deploy the new pods.

Kubernetes Pod Affinity & Pod Anti Affinity Example

apiVersion: v1
kind: Pod
metadata:
  name: with-pod-affinity
spec:
  affinity:
    podAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: security
            operator: In
            values:
            - S1
        topologyKey: failure-domain.beta.kubernetes.io/zone
    podAntiAffinity:
      preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchExpressions:
            - key: security
              operator: In
              values:
              - S2
          topologyKey: failure-domain.beta.kubernetes.io/zone
  containers:
  - name: with-pod-affinity
    image: k8s.gcr.io/pause:2.0

In this example, the podAffinity is required while the podAntiAffinity is preferred

The pod affinity rule indicates that the pod can schedule onto a node only if that node has at least one already-running pod with a label that has the key security and value S1. The pod anti-affinity rule says that the pod prefers not to be scheduled onto a node if that node is already running a pod with label having key “security” and value “S2”. Here the “preferred” rule says that among the nodes that meet “required” criteria, Scheduler will prefer the Pod to be placed on the nodes(required) that have a running pod label with the key “security” and value “s2” Because this rule is “preferred,” if there are no such nodes, the Pod will still be scheduled if the “required” rule is met.

  • Kubernetes pod affinity
  • pod affinity kubernetes
  • kubernetes pod anti affinity
  • Kubernetes pod affinity example
  • pod anti affinity kubernetes
  • Kubernetes pod affinity example

 

Leave a Reply

Your email address will not be published. Required fields are marked *