本文最后更新于:2023年12月5日 晚上
HPA:Horizontal Pod Autoscaler,pod 的自动水平伸缩,特别适合无状态服务
HPA 会自动完成 pod 的扩缩容,当资源需求过高时,会自动创建出 pod 副本;当资源需求低时,会自动收缩 pod 副本数。
注意:通过集群内的资源监控系统(metrics-server),来获取集群中资源的使用状态,所以必须确保集群中已经安装 metrics-server 的组件
HPA 版本:
$kubectl api-versions | grep auto
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
metrics-server 概念 Metrics Server 是 Kubernetes 集群核心监控数据的聚合器,Metrics Server 从 Kubelet 收集资源指标,并通过 Merics API 在 Kubernetes APIServer 中提供给缩放资源对象 HPA 使用。也可以通过 Metrics API 提供的 Kubectl top 查看 Pod 资源占用情况,从而实现对资源的自动缩放。
Metrics Server 是 Kubernetes 监控组件中的重要一部分,Metrics Server 主要分为 API 和 Server 两大部分。
Metrics API:通过 APIServer 对外暴露 Pod 资源使用情况。为 HPA、kubectl top、Kubernetes dashboard 等提供数据来源
Metrics Server :定期通过 Summary API 从 Kubelet 所在集群节点获取服务指标,然后将指标汇总、存储到内存中,仅仅存储指标最新状态,一旦重启组件数据将会丢失
部署 最新的 metrics-server 是 v4.0.2,但是其依赖的镜像需要翻墙,而阿里云镜像和 mirrorgooglecontainers 中都没有最新版本,最新的只有 v0.3.6 版本,勉强用吧
$docker pull registry.aliyuncs.com/google_containers/metrics-server-amd64:v0.3.6
$docker tag registry.aliyuncs.com/google_containers/metrics-server-amd64 harbor.ljk.local/k8s/metrics-server-amd64:v0.3.6
$docker push harbor.ljk.local/k8s/metrics-server-amd64:v0.3.6
$wget https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.3.6/components.yaml
$vim components.yaml
.. .
image: harbor.ljk.local/k8s/metrics-server-amd64:v0.3.6
.. .
$kubectl apply -f components.yaml
$nohup kubectl proxy &
$curl http://localhost:8001/apis/metrics.k8s.io/v1beta1/nodes
$curl http://localhost:8001/apis/metrics.k8s.io/v1beta1/pods
$kubectl top node
$kubectl top pod -A
HPA 示例 要求:我有个 deployment 叫 myapp 现在只有一个副本数,最多只能 8 个副本数,当 pod 的 cpu 平均利用率超过百分之 50 或内存平均值超过百分之 50 时,pod 将自动增加副本数以提供服务
SVC、Deployment 资源清单:
apiVersion : v1
kind : Service
metadata :
name : svc- hpa
namespace : default
spec :
selector :
app : myapp
type : NodePort
ports :
- name : http
port : 80
---
apiVersion : apps/v1
kind : Deployment
metadata :
name : myapp
namespace : default
spec :
replicas : 1
selector :
matchLabels :
app : myapp
template :
metadata :
name : myapp- demo
namespace : default
labels :
app : myapp
spec :
containers :
- name : myapp
image : ikubernetes/myapp: v1
imagePullPolicy : IfNotPresent
ports :
- name : http
containerPort : 80
resources :
requests :
cpu : 50m
memory : 50Mi
limits :
cpu : 50m
memory : 50Mi
HPA 资源清单:
apiVersion : autoscaling/v2beta1
kind : HorizontalPodAutoscaler
metadata :
name : myapp- hpa- v2
namespace : default
spec :
minReplicas : 1
maxReplicas : 8
scaleTargetRef :
apiVersion : apps/v1
kind : Deployment
name : myapp
metrics :
- type : Resource
resource :
name : cpu
targetAverageUtilization : 50
- type : Resource
resource :
name : memory
targetAverageUtilization : 50