kubectl autoscale 是 Kubernetes 中用于快速创建 Horizontal Pod Autoscaler (HPA) 对象的命令。它的主要作用是根据 CPU 或内存使用率等指标,自动调整 Deployment、ReplicaSet 或 StatefulSet 等资源的 Pod 副本数量,以实现应用的弹性伸缩
kubectl autoscale [资源类型]/[资源名称] --min=[最小副本数] --max=[最大副本数] --cpu-percent=[目标CPU使用率] -n [命名空间]
如
| 参数 | 作用 | 示例 |
|---|---|---|
| 资源类型/名称 | deployment/apache-server |
|
--min |
--min=2 |
|
--max |
--max=10 |
|
--cpu-percent |
--cpu-percent=80 |
|
-n / --namespace |
指定资源所在的命名空间。 | -n autoscale |
autoscale 命名空间中的 apache-server Deployment 创建一个 HPA。kubectl autoscale deployment/apache-server \
--min=1 \
--max=10 \
--cpu-percent=80 \
-n autoscale
创建 HPA 后,你可以使用以下命令来检查和验证其状态。
1. 查看 HPA 状态
kubectl get hpa apache-server -n autoscale
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
apache-server Deployment/apache-server 0%/80% 1 10 1 1m
2. 实时监控 HPA
使用 -w 参数可以实时观察 HPA 如何根据负载变化调整副本数1。
kubectl get hpa apache-server -n autoscale -w
3. 删除 HPA
如果需要移除自动伸缩配置,可以使用 delete 命令。
kubectl delete hpa apache-server -n autoscale
kubectl autoscale 命令依赖于 Metrics Server 组件来获取 Pod 的 CPU 和内存使用数据。- 必须安装 Metrics Server:如果你的集群没有安装 Metrics Server,HPA 将无法获取指标数据,
TARGETS列会显示为<unknown>,自动伸缩功能也会失效。 - Pod 需配置资源请求:目标 Pod 的容器定义中必须设置
resources.requests.cpu,否则 HPA 无法计算 CPU 使用率
实战案例:
在 autoscale namespace 中创建一个名为 apache-server 的新HorizontalPodAutoscaler(HPA)此 HPA 必须定位到 autoscale namespace 中名为 apache-server
的现有 Deployment 。
将 HPA 设置为每个 Pod 的 CPU 使用率旨在 50% 。将其配置为至少有 1 个 Pod,且不超过 4 个 Pod 。此外,将缩小稳定窗口设置为 30 秒。
实操:
kubectl -n autoscale autoscale deployment/apache-server --min=1 --max=4 --cpu=50%
检查:
kubectl get hpa apache-server -n autoscale

然后我们参考文档
设置 稳定窗口设置
文档在这:
https://kubernetes.io/zh-cn/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/

找到文档后,
kubectl edit hpa apache-server -n autoscale
注意:

然后保存退出就可以了。
检查:
kubectl get hpa apache-server -n autoscale
然后退出:别忘记,做完后,退回到base 节点,这样下一道题才能继续切节点。
exit

欢迎来撩 : 汇总all

