环境准备
HPA依赖监控服务,默认监控使用metris-server,因此先要部署metrics-server
一、创建Deployment和Service
apiVersion: apps/v1
kind: Deployment
metadata:
name: ngx-dep
spec:
replicas: 1
selector:
matchLabels:
app: ngx-dep
template:
metadata:
labels:
app: ngx-dep
spec:
containers:
- image: nginx:alpine
name: nginx
ports:
- containerPort: 80
resources:
requests:
cpu: 50m
memory: 10Mi
limits:
cpu: 100m
memory: 20Mi
---
apiVersion: v1
kind: Service
metadata:
name: ngx-svc
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: ngx-dep
二、创建HPA
targetCPUUtilizationPercentage: 所有podCPU负载之和/所有pod CPU requests之和
pod自动扩容至平均每个pod负载低于targetCPUUtilizationPercentage。
公式:期望副本数 = ceil[当前副本数 * (当前指标 / 期望指标)]
例如,如果当前指标值为 200m,而期望值为 100m,则副本数将加倍, 因为 200.0 / 100.0 == 2.0 如果当前值为 50m,则副本数将减半, 因为 50.0 / 100.0 == 0.5。如果比率足够接近 1.0(在全局可配置的容差范围内,默认为 0.1), 则控制平面会跳过扩缩操作。
autoscaling提供了两个版本,v2拓展了支持的metrics类型,可以使用Prometheus等系统提供的metrics,详见官方文档:Pod水平自动扩缩
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
name: ngx-hpa
spec:
maxReplicas: 10
minReplicas: 2
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: ngx-dep
targetCPUUtilizationPercentage: 100
v2 API如下:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: ngx-hpa
spec:
maxReplicas: 10
minReplicas: 2
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: ngx-dep
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 100
三、测试
## 使用hpptd提供的apache benchmark
kubectl run test -it --image=httpd:alpine -- sh
## 发送100w个请求
ab -c 10 -t 60 -n 1000000 'http://ngx-svc/'
结果:
可以观察到期初pod为1个,检测到pod指标后自动扩容到最小pod数2个,随后随着压力增大,知道扩容至9个,在流量高峰过后,逐步缩容至2个。
四、常用观察指令
kubectl apply -f ngx-dep.yaml
kubectl apply -f ngx-hpa.yaml
watch -n 1 "kubectl top pod"
kubectl get hpa -w