K8S集群Pod动态弹性扩缩容(HPA )部署
K8S集群Pod动态弹性扩缩容(HPA )部署
一、安装metrics-server
①开启API Aggregator
开启 API Aggregator(API 聚合层)是为了让 Kubernetes 能够安全、标准地集成第三方扩展 API,metrics-server 就是通过这种方式提供
metrics.k8s.ioAPI 的。
vim/etc/kubernetes/manifests/kube-apiserver.yaml#添加这行- --enable-aggregator-routing=true修改 manifests 配置后 API Server 会自动重启生效
②验证配置生效
使用kubectl describe命令来查看 kube-apiserver 的 Pod 描述,确认是否包含了相应的配置。
kubectl describe pod kube-apiserver-k8s-master-nkube-syste二、下载 components.yaml
github地址:Releases · kubernetes-sigs/metrics-server
wgethttps://github.com/kubernetes-sigs/metrics-server/releases/download/v0.8.1/components.yaml①修改配置
下载后修改如下配置,用于跳过证书校验,不加可能会报错
---kubelet-insecure-tls②更换镜像
修改image地址为阿里云镜像源
image:registry.aliyuncs.com/google_containers/metrics-server:v0.6.1③开始安装
kubectl apply-fcomponents.yaml#查看pod状态kubectl get pod-nkube-system|grepmetrics-server④查看node和pod资源使用情况
kubectltopnodes kubectltoppods-nkube-system所有验证都通过了,metrics-server 已经完全正常工作!
三、部署HPA测试应用:php-apache
①下载php-apache.yaml
使用 Kubernetes 官方 HPA 示例:
#下载原始YAML文件wgethttps://k8s.io/examples/application/php-apache.yaml②修改镜像
sed-i's|registry.k8s.io/hpa-example|mirrorgooglecontainers/hpa-example|'php-apache.yaml关键参数说明
- 镜像:
mirrorgooglecontainers/hpa-example- 设置了
resources.requests.cpu: 200m(HPA 必需)- 暴露 Service
php-apache供压测
③应用配置
kubectl apply-fphp-apache.yaml④验证
kubectl get deploy/php-apache kubectl describe pod-lrun=php-apache|grep-A5"Requests"四、创建HorizontalPodAutoscaler
kubectl autoscale deployment php-apache --cpu-percent=50--min=1--max=10--cpu-percent=50:目标 CPU 利用率为 50%(基于 requests 计算)- 副本数范围:1 ~ 10
查看状态
root@k8s-master:/data/k8s/hpa# kubectl get hpaNAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE php-apache Deployment/php-apache cpu:0%/50%110115h若显示
<unknown>/50%,请检查:
- Metrics Server 是否运行正常(
kubectl top pods)- Pod 是否设置了
resources.requests.cpu
五、压测验证HPA自动扩缩容
①启动负载生成器(新开终端)
kubectl run-i--ttyload-generator--rm\--image=busybox:1.28\--restart=Never\-- /bin/sh-c"while sleep 0.01; do wget -q -O- http://php-apache; done"②实时观察HPA行为
kubectl get hpa php-apache --watch典型扩缩容过程:
行为说明:
- 扩容响应较快(秒级)
- 缩容有默认 5 分钟冷却期(由
--horizontal-pod-autoscaler-downscale-stabilization控制)
③停止压测
在负载终端按Ctrl + C,Pod 自动清理。
