K8S自动扩容和缩容
1、扩容的背景分析
-
背景:
- 弹性伸缩是根据业务需求来自动的调节资源大小,保证业务的平稳运行。
-
在K8S中扩容和缩容分为两个层面
-
Node层面:
- 对K8S节点进行扩容和缩容,根据业务量实现节点的自动扩容和缩容
-
Pod层面
- 在pod上一般会设置多个副本集来保证服务的高可用,不管是在平时流量比较少时,还是在某个时间段流量突然暴增,这个值都是固定的,这样不利于应对流量暴增的突发情况。这种就需要用到K8S的自动扩容和缩容。
-
2、自动扩容的步骤(基于HPA)
[root@k8s-master1 test]# kubectl create deployment web1 --image=nginx --dry-run=client -o yaml > web1.yaml
[root@k8s-master1 test]# kubectl expose -f web1.yaml --port=80 --target-port=80 --type=NodePort --dry-run=client -o yaml
[root@k8s-master1 test]# vim web1.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: web1
name: web1
spec:
replicas: 3
selector:
matchLabels:
app: web1
strategy: {}
template:
metadata:
labels:
app: web1
spec:
containers:
- image: nginx
name: nginx
resources:
requests:
cpu: 100m
memory: 300Mi
limits:
cpu: 500m
memory: 1Gi
---
apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
name: web1
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: web1
type: NodePort
[root@k8s-master1 test]# kubectl apply -f web1.yaml
[root@k8s-master1 test]# yum install httpd-tools -y
# web1为deployment的名字,cpu-percent=10指的是cpu利用率不超过10%,min为副本数最低为1,max为副本数最大为6
[root@k8s-master1 test]# kubectl autoscale deployment web1 --cpu-percent=10 --min=1 --max=6
# 在另一台节点上进行压测
[root@k8s-node2 ~]# ab -n 100000 -c 100 10.0.0.61/ok
# 实时观测cpu变化情况
[root@k8s-master1 test]# kubectl get hpa -w
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
web1 Deployment/web1 0%/10% 1 6 1 17m
web1 Deployment/web1 44%/10% 1 6 1 17m
web1 Deployment/web1 502%/10% 1 6 4 17m
web1 Deployment/web1 374%/10% 1 6 6 17m
web1 Deployment/web1 0%/10% 1 6 6 17m
# 等待pod进行扩容
[root@k8s-master1 test]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nfs-client-provisioner-7fd757df9d-qn4n2 1/1 Running 82 (28m ago) 43d
web1-dbd8d8496-7ll6m 1/1 Running 0 18h
web1-dbd8d8496-flf62 1/1 Running 0 45s
web1-dbd8d8496-gw9gs 1/1 Running 0 30s
web1-dbd8d8496-m7sgw 1/1 Running 0 45s
web1-dbd8d8496-mn5df 1/1 Running 0 30s
web1-dbd8d8496-wh2b2 1/1 Running 0 45s
[root@k8s-master1 ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nfs-client-provisioner-7fd757df9d-qn4n2 1/1 Running 82 (33m ago) 43d
web1-dbd8d8496-7ll6m 1/1 Running 0 18h
注意:HPA中默认扩容冷却时间为3分钟,缩容冷却周期为5分钟。可以自己设置