Kubernetes pod affinity

Similar to node affinity, pod affinity is mainly used to restrict the work of the scheduler. As the name suggests, pod affinity is scheduled with reference to the operation of pod

Instead of controlling scheduling according to nodes like node affinity

In kubernetes node affinity, we created the deploy of nginx

You can see that nginx is all running on 129

Here we try to make nginx2 follow nginx scheduling on the same node

use

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-hello-deployment2
  namespace: lizhe
  labels:
    app: nginx-hello2
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-hello2
  template:
    metadata:
      labels:
        app: nginx-hello2
    spec:
      affinity:
        podAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - nginx-hello
            topologyKey: numberCores
      containers:
      - name: nginx-hello2
        image: nginx
        ports:
        - containerPort: 80

It is found that nginx2 is not only scheduled on 129, but also scheduled on 139

We have to talk about topologykey, because our three nodes specify numbercores = 6

in other words,

On the node running pod app=nginx-hello with numbercores and a value of 6

As long as it is a node with numbercores of 6, nginx2 can be run

We change numbercores to 7 on 129, so that only numbercores of 129 is 7 and other nodes are 6

In this way, nginx2 can only be scheduled on 129 in order to follow nginx 7

Because the affinity configuration cannot take effect again on the created pod (because it has been scheduled)

So here we delete the original dep and recreate it

This time, you can see that because only 129 has 7, nginx is all scheduled on 129

If you want pod a to be scheduled only on the node that has run pod B, you just need to

Topologykey is written as kubernetes io/hostname

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-hello-deployment2
  namespace: lizhe
  labels:
    app: nginx-hello2
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx-hello2
  template:
    metadata:
      labels:
        app: nginx-hello2
    spec:
      affinity:
        podAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - nginx-hello
            topologyKey: kubernetes.io/hostname
      containers:
      - name: nginx-hello2
        image: nginx
        ports:
        - containerPort: 80
Send a Message