Kubernetes Pod Affinity rules in a nutshell

bzon

Bryan Sazon

Posted on February 6, 2020

Kubernetes Pod Affinity rules in a nutshell

Pod Affinity

If you have the time, you must read about Pod Affinity.

Problem

I do not want to run a specific workload (sensitive-workload) along with some disruptive workloads (mysql and prometheus) within the same node. I know that these disruptive workloads have the following pod labels:

  • app=mysql (default namespace)
  • app=prometheus (monitoring namespace)
kubectl get pods -l app=mysql -n default
kubectl get pods -l app=prometheus -n monitoring

Solution:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: sensitive-workload
  namespace: default
spec:
  template:
    metadata:
      labels:
        app: sensitive-workload
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - mysql
            topologyKey: "kubernetes.io/hostname"
          - labelSelector:
              matchExpressions:
                - key: app
                  operator: In
                  values:
                  - prometheus
            topologyKey: "kubernetes.io/hostname"
            namespaces:
              - monitoring

By default labelSelector will search within the same namespace of the workload. You can use the namespaces field to add more namespaces to look for.

💖 💪 🙅 🚩
bzon
Bryan Sazon

Posted on February 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related