背景
一句话说明需求:
- K8S中同一个Deploy的不同Pod部署到不同的Node上。
- (或)K8S中同一个Deploy的不同replicas部署到不同的Node上。
- (或)K8S中同一个应用的不同容器部署到不同的Node上。
一句话说明解决:
- 使用K8S的“亲和性Affinity”、“反亲和性AntiAffinity”可以实现Pod/replicas/容器在不同K8S-node上的部署。
短话长说:
- 因为需要对微服务进行压力测试,为避免压力测试瓶颈受限于“同一个微服务的多个Pod实例(容器)位于同一台Node上”,故需要将多个Pod实例(容器)分别置于多台Node上,进一步可以测试横向扩展更多Pod实例(容器),观察相关压力测试的情况。
参考文章
实际操作
基础知识
- 什么是Label?
- 什么是selector?
- 什么是affinity?
- affinity的四种规则表达式是什么?
以上问题稍后补充,为解决问题可直接参考本文后续内容。
实例验证
不看基础知识,直接按照下列步骤操作也行,可以直接解决问题。
节选部分字段,修改相关内容即可。依次在Deployment.spec.template.spec.affinity.podAntiAffinity.requiredDuringSchedulingIgnoredDuringExecution
中新增lableSelector字段,填写匹配标签和匹配规则即可。
修改前deploy如下:(此时不同Pod位于同一台Node上)
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: apps/v1
kind: Deployment
metadata:
#(metadata字段内容省略)
spec:
progressDeadlineSeconds: 600
replicas: 2
revisionHistoryLimit: 10
selector:
matchLabels:
k8s-app: socketioservice
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
annotations:
kubectl.kubernetes.io/restartedAt: "2023-10-06T10:04:58Z"
creationTimestamp: null
labels:
consul: consulclient
k8s-app: socketioservice
spec:
containers:
- env:
- name: CONSUL_HOST
value: 127.0.0.1
- name: CONSUL_PORT
value: "8500"
#(容器字段内内环境变量内容省略)
#(模板字段内dnsPolicy、imagePullSecrets、restartPolicy、schedulerName等网络、调度内容省略)
status:
#(status字段内容省略)
修改后deploy如下:(此时不同Pod将位于不同的Node上)
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: apps/v1
kind: Deployment
metadata:
#(metadata字段内容省略)
spec:
progressDeadlineSeconds: 600
replicas: 2
revisionHistoryLimit: 10
selector:
matchLabels:
k8s-app: socketioservice
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
annotations:
kubectl.kubernetes.io/restartedAt: "2023-10-06T10:04:58Z"
creationTimestamp: null
labels:
consul: consulclient
k8s-app: socketioservice
####################新增内容-start##############
spec:
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: k8s-app
operator: In
values:
- socketioservice #修改此处,改为你的微服务名即可
topologyKey: kubernetes.io/hostname
#####################新增内容-end##############
containers:
- env:
- name: CONSUL_HOST
value: 127.0.0.1
- name: CONSUL_PORT
value: "8500"
#(容器字段内内环境变量内容省略)
#(模板字段内dnsPolicy、imagePullSecrets、restartPolicy、schedulerName等网络、调度内容省略)
status:
#(status字段内容省略)
相关截图
新增affinity字段的位置如下图:
修改前两个pod位于同一台K8S-node上,如下图:
修改的内容如下:
修改成功后,pod和容器需要重启并重新分布到不同的K8S-node上,如下图:
注意:原有的多个Pod都会被销毁重新创建,并不是将其中之一挪到另一个K8S-node上。