Horizontal Pod Autoscaling水平Pod自动缩放
在Kubernetes中,Horizontal Pod Autoscaler自动更新工作负载资源,目的是自动扩展/缩放工作负载以满足需求。
水平扩展意味着对增加负载的响应是部署更多的Pods。这不同于垂直扩展,对于Kubernetes来说,垂直扩展意味着将更多的资源(例如:内存或CPU)分配给已经在为工作负载运行的Pods。
如果负载减少,并且pods的数量高于配置的最小值,Horizontal Pod Autoscaler会指示工作负载资源(部署、StatefulSet或其他类似资源)缩减。
Horizontal Pod Autoscaler自动缩放不适用于无法缩放的对象(例如:DaemonSet。)
运行一个nginx Web服务
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
namespace: openeuler
labels:
app: web1
name: web1
spec:
replicas: 1
selector:
matchLabels:
app: web1
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
app: web1
spec:
terminationGracePeriodSeconds: 0
containers:
- image: nginx
name: nginx
imagePullPolicy: IfNotPresent
resources:
requests:
cpu: 150m
status: {}
创建deployment
kubectl apply -f web1.yaml
创建Service
kubectl expose deployment -n openeuler web1 --port 8080 --target-port 80 --type NodePort
创建Horizontal Pod Autoscaler
HPA控制器将增加和减少副本的数量(通过更新部署),以保持所有Pods的平均CPU利用率为50%。然后部署更新ReplicaSet——这是Kubernetes中所有部署工作的一部分,然后ReplicaSet根据对其.spec的更改添加或删除pod。
创建HorizontalPodAutoscaler
kubectl autoscale deployment -n openeuler web1 --max=5 --cpu-percent 50 -n openeuler
检查hpa
kubectl get hpa -n openeuler
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
web1 Deployment/web1 0%/50% 1 5 1 28h
增加负载
在一台主机上安装httpd-tools
,使用命令ab请求,增加负载
yum -y install httpd-tools
增加负载测试
ab -t 600 -n 1000000 -c 100 http://192.168.26.129:30552/
观察hpa变化
kubectl get hpa -n openeuler -w
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
web1 Deployment/web1 0%/50% 1 5 1 28h
web1 Deployment/web1 12%/50% 1 5 1 28h
web1 Deployment/web1 280%/50% 1 5 1 28h
web1 Deployment/web1 280%/50% 1 5 4 28h
web1 Deployment/web1 280%/50% 1 5 5 28h
web1 Deployment/web1 159%/50% 1 5 5 28h
web1 Deployment/web1 59%/50% 1 5 5 28h
web1 Deployment/web1 57%/50% 1 5 5 28h
web1 Deployment/web1 58%/50% 1 5 5 28h
web1 Deployment/web1 57%/50% 1 5 5 28h
web1 Deployment/web1 53%/50% 1 5 5 28h
web1 Deployment/web1 54%/50% 1 5 5 28h
web1 Deployment/web1 50%/50% 1 5 5 28h
web1 Deployment/web1 53%/50% 1 5 5 28h
web1 Deployment/web1 58%/50% 1 5 5 28h
web1 Deployment/web1 56%/50% 1 5 5 28h
web1 Deployment/web1 57%/50% 1 5 5 28h
web1 Deployment/web1 53%/50% 1 5 5 28h
web1 Deployment/web1 58%/50% 1 5 5 28h
web1 Deployment/web1 44%/50% 1 5 5 28h
web1 Deployment/web1 54%/50% 1 5 5 28h
web1 Deployment/web1 59%/50% 1 5 5 28h
web1 Deployment/web1 49%/50% 1 5 5 28h
web1 Deployment/web1 54%/50% 1 5 5 28h
web1 Deployment/web1 58%/50% 1 5 5 28h
web1 Deployment/web1 30%/50% 1 5 5 28h
web1 Deployment/web1 0%/50% 1 5 5 28h
web1 Deployment/web1 0%/50% 1 5 5 28h
Pods增加
kubectl get pods -n openeuler
NAME READY STATUS RESTARTS AGE
web1-6d5bd5bdbf-2k5dv 1/1 Running 0 48s
web1-6d5bd5bdbf-4nq8q 1/1 Running 0 48s
web1-6d5bd5bdbf-bdlxl 1/1 Running 0 48s
web1-6d5bd5bdbf-gh6gq 1/1 Running 0 33s
web1-6d5bd5bdbf-xbxl6 1/1 Running 1 (25m ago) 5h2m
通过测试,hpa负载逐步增加,Pod数量增加到5个,测试结束后,hpa负载逐步减少,最后pods数量减少到1个Pod。