当前集群信息:
root@k8s-master:~# kubectl get node -o wide
NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME
k8s-master Ready control-plane,master 683d v1.22.0 192.168.123.150 Ubuntu 18.04.5 LTS 4.15.0-213-generic docker://20.10.0
k8s-node1 Ready 683d v1.22.0 192.168.123.151 Ubuntu 18.04.5 LTS 4.15.0-213-generic docker://20.10.0
k8s-node2 Ready 683d v1.22.0 192.168.123.152 Ubuntu 18.04.5 LTS 4.15.0-213-generic docker://20.10.0
列出集群节点及标签
root@k8s-master:~# kubectl get node --show-labels
NAME STATUS ROLES AGE VERSION LABELS
k8s-master Ready control-plane,master 683d v1.22.0 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-master,kubernetes.io/os=linux,node-role.kubernetes.io/control-plane=,node-role.kubernetes.io/master=,node.kubernetes.io/exclude-from-external-load-balancers=
k8s-node1 Ready 683d v1.22.0 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disk=ssd,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node1,kubernetes.io/os=linux
k8s-node2 Ready 683d v1.22.0 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disk=ssd,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node2,kubernetes.io/os=linux
选择一个节点,给它添加标签(这里我选择node1节点):
root@k8s-master:~# kubectl label nodes k8s-node1 nodetype=dev
node/k8s-node1 labeled
root@k8s-master:~# kubectl get node k8s-node1 --show-labels
NAME STATUS ROLES AGE VERSION LABELS
k8s-node1 Ready 683d v1.22.0 beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,disk=ssd,kubernetes.io/arch=amd64,kubernetes.io/hostname=k8s-node1,kubernetes.io/os=linux,nodetype=dev
这里给node1打上nodetype=dev
标签
下面清单描述了一个 Pod,它有一个节点亲和性配置
requiredDuringSchedulingIgnoredDuringExecution
,nodetype=dev
。 这意味着 pod 只会被调度到具有nodetype=dev
标签的节点上。
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: nodetype
operator: In
values:
- dev
containers:
- name: nginx
image: nginx
imagePullPolicy: IfNotPresent
通过此yml文件执行,发现刚刚创建的Pod在node1节点执行
root@k8s-master:~# kubectl get pod -o wide | grep k8s-node1
nginx 1/1 Running 0 77s 10.244.36.68 k8s-node1
本清单描述了一个 Pod,它有一个节点亲和性设置
preferredDuringSchedulingIgnoredDuringExecution
,nodetype=dev
。 这意味着 Pod 将首选具有nodetype=dev
标签的节点。
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 1
preference:
matchExpressions:
- key: disktype
operator: In
values:
- ssd
containers:
- name: nginx
image: nginx
imagePullPolicy: IfNotPresent