Kubernetes 之 Pod 之间的亲和性与反亲和性
Pod 亲和性定义
Pod 亲和性是指将 Pod 和 Pod 根据某些约束性条件捆绑到具有相同特性的工作节点上,例如同一区域、同一机房乃至同一机柜。这样 Pod和 Pod 可以更好的通信,解决 IO 瓶颈。它同样分为硬亲和性requiredDuringSchedulingIgnoredDuringExecution
和软亲和性preferredDuringSchedulingIgnoredDuringExecution
,同时亲和性下面还有一个拓扑键topologyKey
,这是用来将 Pod 约束到跟跟随 Pod 同一个域上的。
Pod 亲和性使用
-
我们先定义一个被跟随的 Pod
yamlapiVersion: v1 kind: Pod metadata: name: pod-affinity-bind namespace: default labels: app: nginx spec: containers: - name: k8s-test image: k8s-test:v1.0 imagePullPolicy: IfNotPresent ports: - containerPort: 80
-
定义 Pod 去跟随第一个 Pod
yamlapiVersion: v1 kind: Pod metadata: name: pod-affinity-track namespace: default labels: app: track spec: affinity: podAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: app operator: In values: - nginx topologyKey: kubernetes.io/hostname containers: - name: k8s-test image: k8s-test:v1.0 imagePullPolicy: IfNotPresent ports: - containerPort: 80
-
运行结果
root@k8s-master1:~# kubectl get pods -owide --show-labels NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES LABELS pod-affinity-bind 1/1 Running 0 25m 10.244.194.83 k8s-worker1 <none> <none> app=nginx pod-affinity-track 1/1 Running 0 24s 10.244.194.84 k8s-worker1 <none> <none> app=track
Pod 反亲和性定义
Pod 反亲和性是与亲和性完全相反的定义,一旦发现它的约束条件匹配,那么这个 Pod 比与匹配 Pod 在不同的topologyKey
上的工作节点上。它主要可以用来保障不是热点区域和不需要高性能响应但很重要的业务不受干扰。
Pod 反亲和性使用
yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-affinity-anti
namespace: default
labels:
app: anti
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- nginx
topologyKey: kubernetes.io/hostname
containers:
- name: k8s-test
image: k8s-test:v1.0
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
shell
root@k8s-master1:~# kubectl get pods -owide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod-affinity-anti 1/1 Running 0 8m45s 10.244.126.15 k8s-worker2 <none> <none>
pod-affinity-bind 1/1 Running 0 76m 10.244.194.83 k8s-worker1 <none> <none>
pod-affinity-track 1/1 Running 0 51m 10.244.194.84 k8s-worker1 <none> <none>