针对对象为Pod,目的是实现,新建Pod和目标Pod调度到一起,在同一个Node上。
示例:
bash
root@k8s-master:/home/vagrant# cat pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: testpod01
labels:
app: myapp01
env: test1
spec:
containers:
- name: testpod01
image: nginx:1.23.2
imagePullPolicy: IfNotPresent
root@k8s-master:/home/vagrant# cat pod2.yaml
apiVersion: v1
kind: Pod
metadata:
name: testpod02
labels:
app: myapp02
env: test2
spec:
affinity:
podAffinity:
requiredDuringSchedulingIgnoredDuringExecution: ##必须满足下面匹配规则
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- myapp01 ## app=myapp01, 上面的Pod是符合要求的
topologyKey: "kubernetes.io/hostname"
containers:
- name: testpod02
image: redis:6.2
imagePullPolicy: IfNotPresent
root@k8s-master:/home/vagrant# kubectl create -f pod.yaml
root@k8s-master:/home/vagrant# kubectl create -f pod2.yaml
root@k8s-master:/home/vagrant# kubectl get pods --show-labels -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES LABELS
node-affinity 1/1 Running 0 26m 172.16.126.2 k8s-worker2 <none> <none> <none>
testpod01 1/1 Running 0 8m15s 172.16.194.65 k8s-worker1 <none> <none> app=myapp01,env=test1
testpod02 1/1 Running 0 2m20s 172.16.194.66 k8s-worker1 <none> <none> app=myapp02,env=test2