1.简介
Pod 反亲和性(podAntiAffinity)则是反着来的,比如一个节点上运行了某个 Pod,那么我们的模板 Pod 则不希望被调度到这个节点上面去了。我们把上面的 podAffinity 直接改成 podAntiAffinity:(pod-antiaffinity-demo.yaml)
apiVersion: apps/v1
kind: Deployment
metadata:
name: pod-antiaffinity
labels:
app: pod-antiaffinity
spec:
replicas: 3
selector:
matchLabels:
app: pod-antiaffinity
template:
metadata:
labels:
app: pod-antiaffinity
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
name: nginxweb
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution: # 硬策略
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- busybox-pod
topologyKey: kubernetes.io/hostname
这里的意思就是如果一个节点上面有一个 app=busybox-pod 这样的 Pod 的话,那么我们的 Pod 就别调度到这个节点上面来,上面我们把app=busybox-pod 这个 Pod 固定到了 node2 这个节点上面的,所以正常来说我们这里的 Pod 不会出现在该节点上:
[root@k8s-master01 ~]# kubectl get pod -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
busybox 1/1 Running 264 11d 172.17.125.9 k8s-node01 <none> <none>
nginx-68db656dd8-mprnc 1/1 Running 0 74m 172.17.125.13 k8s-node01 <none> <none>
nginx-68db656dd8-znwgp 1/1 Running 1 11d 172.18.195.11 k8s-master03 <none> <none>
pod-antiaffinity-7bb9c7ff57-4l8dt 1/1 Running 0 17s 172.17.125.16 k8s-node01 <none> <none>
pod-antiaffinity-7bb9c7ff57-kq4gj 0/1 ContainerCreating 0 17s <none> k8s-node01 <none> <none>
pod-antiaffinity-7bb9c7ff57-zhg2q 1/1 Running 0 17s 172.25.244.217 k8s-master01 <none> <none>
test-busybox 1/1 Running 0 23m 172.27.14.239 k8s-node02 <none> <none>
web 2/2 Running 0 3d19h 172.18.195.14 k8s-master03 <none> <none>
我们可以看到没有被调度到 node2 节点上,因为我们这里使用的是 Pod 反亲和性。大家可以思考下,如果这里我们将拓扑域更改成 beta.kubernetes.io/os 会怎么样呢?答案是:Pending
[root@k8s-master01 ~]# kubectl get pod -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
busybox 1/1 Running 264 11d 172.17.125.9 k8s-node01 <none> <none>
nginx-68db656dd8-mprnc 1/1 Running 0 77m 172.17.125.13 k8s-node01 <none> <none>
nginx-68db656dd8-znwgp 1/1 Running 1 11d 172.18.195.11 k8s-master03 <none> <none>
pod-antiaffinity-64bf798fb6-dvhh2 0/1 Pending 0 9s <none> <none> <none> <none>
pod-antiaffinity-64bf798fb6-rg2pc 0/1 Pending 0 9s <none> <none> <none> <none>
pod-antiaffinity-64bf798fb6-ttnbp 0/1 Pending 0 9s <none> <none> <none> <none>
test-busybox 1/1 Running 0 25m 172.27.14.239 k8s-node02 <none> <none>
web 2/2 Running 0 3d19h 172.18.195.14 k8s-master03 <none> <none>