关键词:
① requiredDuringSchedulingIgnoredDuringExecution:表示强匹配,必须要满足
② preferredDuringSchedulingIgnoredDuringExecution:表示弱匹配,尽可能满足,但不保证
示例:
apiVersion: v1
kind: Pod
metadata:name: with-node-affinity
spec:affinity:nodeAffinity:requiredDuringSchedulingIgnoredDuringExecution: ##必须满足下面匹配规则nodeSelectorTerms:- matchExpressions:- key: envoperator: In ##逻辑运算符支持:In,NotIn,Exists,DoesNotExist,Gt,Ltvalues:- test- devpreferredDuringSchedulingIgnoredDuringExecution: ##尽可能满足,但不保证- weight: 1preference:matchExpressions:- key: projectoperator: Invalues:- aminglinuxcontainers:- name: with-node-affinityimage: redis:6.0.6
说明:
匹配逻辑:
① 同时指定Node Selector和Node Affinity,两者必须同时满足;
② Node Affinity中指定多组nodeSelectorTerms,只需要一组满足就可以;
③ 当在nodeSelectorTerms中包含多组matchExpressions,必须全部满足才可以;
演示示例:
编辑pod的yaml
cat > nodeAffinity.yaml << EOF
apiVersion: v1
kind: Pod
metadata:name: node-affinity
spec:containers:- name: my-containerimage: nginx:1.23.2affinity:nodeAffinity:requiredDuringSchedulingIgnoredDuringExecution:nodeSelectorTerms:- matchExpressions:- key: special-nodeoperator: Exists
EOF给其中一个节点定义标签
kubectl label nodes k8s-worker2 special-node=true生效Pod yaml
kubectl apply -f nodeAffinity.yaml检查Pod所在node
root@k8s-master:/home/vagrant# kubectl get po -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
node-affinity 1/1 Running 0 3m47s 172.16.126.2 k8s-worker2 <none> <none>