HorizontalPodAutoscaler 演练
HorizontalPodAutoscaler(简称 HPA)会自动更新工作负载资源(例如Deployment或StatefulSet),目的是自动缩放工作负载以匹配需求。
水平缩放意味着对负载增加的响应是部署更多Pod。这与垂直缩放不同,后者对于 Kubernetes 来说意味着为工作负载已经运行的 Pod 分配更多资源(例如:内存或 CPU)。
如果负载减少,并且 Pod 的数量高于配置的最小值,则 HorizontalPodAutoscaler 会指示工作负载资源(Deployment、StatefulSet 或其他类似资源)缩减规模。
本文档将引导您完成一个示例,该示例演示如何启用 HorizontalPodAutoscaler 以自动管理示例 Web 应用程序的扩展。此示例工作负载是运行某些 PHP 代码的 Apache httpd。
开始之前
你需要有一个 Kubernetes 集群,并且必须配置 kubectl 命令行工具才能与你的集群通信。建议在至少有两个节点且不充当控制平面主机的集群上运行本教程。如果还没有集群,可以使用minikube创建一个,也可以使用以下 Kubernetes 游乐场之一
你的 Kubernetes 服务器必须是 1.23 或更高版本。要检查版本,请输入kubectl version。如果运行的是旧版本的 Kubernetes,请参考该版本的文档(请参阅可用的文档版本)。要遵循本演练,你还需要使用一个已部署并配置了指标服务器的集群。Kubernetes 指标服务器从你集群中的kubelet收集资源指标,并通过Kubernetes API公开这些指标,使用APIService添加表示指标读数的新资源类型。
要了解如何部署指标服务器,请参阅指标服务器文档。
如果你正在运行Minikube,请运行以下命令以启用指标服务器
minikube addons enable metrics-server
运行并暴露 php-apache 服务器
为了演示 HorizontalPodAutoscaler,你将首先启动一个 Deployment,该 Deployment 使用 hpa-example 镜像运行容器,并使用以下清单将其暴露为服务
apiVersion: apps/v1
kind: Deployment
metadata:
name: php-apache
spec:
selector:
matchLabels:
run: php-apache
template:
metadata:
labels:
run: php-apache
spec:
containers:
- name: php-apache
image: registry.k8s.io/hpa-example
ports:
- containerPort: 80
resources:
limits:
cpu: 500m
requests:
cpu: 200m
---
apiVersion: v1
kind: Service
metadata:
name: php-apache
labels:
run: php-apache
spec:
ports:
- port: 80
selector:
run: php-apache
要执行此操作,请运行以下命令
kubectl apply -f https://k8s.io/examples/application/php-apache.yaml
deployment.apps/php-apache created
service/php-apache created
创建 HorizontalPodAutoscaler
现在服务器正在运行,使用 kubectl 创建自动缩放器。 kubectl autoscale 子命令是 kubectl 的一部分,可帮助你执行此操作。
你将很快运行一个命令来创建一个 HorizontalPodAutoscaler,它维护你在这些说明的第一步中创建的 php-apache Deployment 所控制的 Pod 的 1 到 10 个副本。
粗略地说,HPA 控制器 将增加和减少副本的数量(通过更新 Deployment)以维持所有 Pod 的平均 CPU 利用率为 50%。然后,Deployment 会更新 ReplicaSet - 这是 Kubernetes 中所有 Deployment 的工作方式的一部分 - 然后 ReplicaSet 会根据其 .spec 的更改添加或删除 Pod。
由于每个 Pod 通过 kubectl run 请求 200 毫核,这意味着平均 CPU 使用率为 100 毫核。有关该算法的更多详细信息,请参阅算法详情。
创建 HorizontalPodAutoscaler
kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10
horizontalpodautoscaler.autoscaling/php-apache autoscaled
你可以通过运行以下命令来检查新创建的 HorizontalPodAutoscaler 的当前状态
# You can use "hpa" or "horizontalpodautoscaler"; either name works OK.
kubectl get hpa
输出类似于
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 0% / 50% 1 10 1 18s
(如果你看到其他名称不同的 HorizontalPodAutoscaler,则表示它们已经存在,通常不是问题)。
请注意,当前 CPU 消耗为 0%,因为没有客户端向服务器发送请求(TARGET 列显示相应 Deployment 控制的所有 Pod 的平均值)。
增加负载
接下来,看看自动缩放器如何对负载增加做出反应。为此,你将启动另一个 Pod 作为客户端。客户端 Pod 中的容器在无限循环中运行,向 php-apache 服务发送查询。
# Run this in a separate terminal
# so that the load generation continues and you can carry on with the rest of the steps
kubectl run -i --tty load-generator --rm --image=busybox:1.28 --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done"
现在运行
# type Ctrl+C to end the watch when you're ready
kubectl get hpa php-apache --watch
在一分钟左右的时间内,你应该会看到更高的 CPU 负载;例如
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 305% / 50% 1 10 1 3m
然后,更多的副本。例如
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 305% / 50% 1 10 7 3m
在这里,CPU 消耗已增加到请求的 305%。 因此,Deployment 的大小调整为 7 个副本
kubectl get deployment php-apache
你应该看到副本计数与 HorizontalPodAutoscaler 中的数字匹配
NAME READY UP-TO-DATE AVAILABLE AGE
php-apache 7/7 7 7 19m
注意
可能需要几分钟才能稳定副本数量。由于负载量未以任何方式控制,因此最终的副本数量可能与此示例不同。停止生成负载
要完成示例,请停止发送负载。
在你创建运行 busybox 镜像的 Pod 的终端中,键入 <Ctrl> + C 以终止负载生成。
然后验证结果状态(大约一分钟后)
# type Ctrl+C to end the watch when you're ready
kubectl get hpa php-apache --watch
输出类似于
NAME REFERENCE TARGET MINPODS MAXPODS REPLICAS AGE
php-apache Deployment/php-apache/scale 0% / 50% 1 10 1 11m
并且 Deployment 也显示它已经缩减了规模
kubectl get deployment php-apache
NAME READY UP-TO-DATE AVAILABLE AGE
php-apache 1/1 1 1 27m
一旦 CPU 利用率降至 0,HPA 会自动将副本数量缩减回 1。
自动伸缩副本可能需要几分钟时间。
基于多个指标和自定义指标进行自动伸缩
您可以通过使用 autoscaling/v2 API 版本,在自动伸缩 php-apache Deployment 时引入其他指标。
首先,获取 autoscaling/v2 形式的 HorizontalPodAutoscaler 的 YAML。
kubectl get hpa php-apache -o yaml > /tmp/hpa-v2.yaml
在编辑器中打开 /tmp/hpa-v2.yaml 文件,您应该看到如下所示的 YAML:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: php-apache
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: php-apache
minReplicas: 1
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
status:
observedGeneration: 1
lastScaleTime: <some-time>
currentReplicas: 1
desiredReplicas: 1
currentMetrics:
- type: Resource
resource:
name: cpu
current:
averageUtilization: 0
averageValue: 0
请注意,targetCPUUtilizationPercentage 字段已被名为 metrics 的数组替换。CPU 利用率指标是一种资源指标,因为它表示为 Pod 容器上指定的资源百分比。请注意,除了 CPU 之外,您还可以指定其他资源指标。默认情况下,唯一支持的另一个资源指标是 memory。这些资源在集群之间不会更改名称,只要 metrics.k8s.io API 可用,就应该始终可用。
您还可以使用 AverageValue 而不是 Utilization 的 target.type,并通过设置相应的 target.averageValue 字段而不是 target.averageUtilization 来指定直接值的资源指标,而不是请求值的百分比。
metrics:
- type: Resource
resource:
name: memory
target:
type: AverageValue
averageValue: 500Mi
还有另外两种类型的指标,都被认为是自定义指标:Pod 指标和对象指标。这些指标的名称可能是特定于集群的,并且需要更高级的集群监控设置。
第一种替代指标类型是Pod 指标。这些指标描述 Pod,并在 Pod 之间进行平均,并与目标值进行比较以确定副本计数。它们的工作方式很像资源指标,但它们仅支持 AverageValue 的 target 类型。
Pod 指标使用如下所示的指标块指定:
type: Pods
pods:
metric:
name: packets-per-second
target:
type: AverageValue
averageValue: 1k
第二种替代指标类型是对象指标。这些指标描述同一命名空间中的不同对象,而不是描述 Pod。这些指标不一定从对象中获取;它们只是描述它。对象指标支持 Value 和 AverageValue 的 target 类型。对于 Value,目标直接与来自 API 的返回指标进行比较。对于 AverageValue,来自自定义指标 API 的返回值会除以 Pod 的数量,然后再与目标进行比较。以下示例是 requests-per-second 指标的 YAML 表示形式。
type: Object
object:
metric:
name: requests-per-second
describedObject:
apiVersion: networking.k8s.io/v1
kind: Ingress
name: main-route
target:
type: Value
value: 2k
如果您提供多个此类指标块,HorizontalPodAutoscaler 将依次考虑每个指标。HorizontalPodAutoscaler 将计算每个指标的建议副本计数,然后选择副本计数最高的指标。
例如,如果您的监控系统收集有关网络流量的指标,您可以使用 kubectl edit 更新上述定义,如下所示:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: php-apache
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: php-apache
minReplicas: 1
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
- type: Pods
pods:
metric:
name: packets-per-second
target:
type: AverageValue
averageValue: 1k
- type: Object
object:
metric:
name: requests-per-second
describedObject:
apiVersion: networking.k8s.io/v1
kind: Ingress
name: main-route
target:
type: Value
value: 10k
status:
observedGeneration: 1
lastScaleTime: <some-time>
currentReplicas: 1
desiredReplicas: 1
currentMetrics:
- type: Resource
resource:
name: cpu
current:
averageUtilization: 0
averageValue: 0
- type: Object
object:
metric:
name: requests-per-second
describedObject:
apiVersion: networking.k8s.io/v1
kind: Ingress
name: main-route
current:
value: 10k
然后,您的 HorizontalPodAutoscaler 将尝试确保每个 Pod 消耗大约其请求的 CPU 的 50%,每秒处理 1000 个数据包,并且主路由 Ingress 后面的所有 Pod 总共每秒处理 10000 个请求。
基于更具体的指标进行自动伸缩
许多指标管道允许您通过名称或一组称为标签的附加描述符来描述指标。对于所有非资源指标类型(Pod、对象和外部,如下所述),您可以指定一个附加的标签选择器,该选择器将传递到您的指标管道。例如,如果您收集带有 verb 标签的指标 http_requests,您可以指定以下指标块仅基于 GET 请求进行缩放:
type: Object
object:
metric:
name: http_requests
selector: {matchLabels: {verb: GET}}
此选择器使用与完整 Kubernetes 标签选择器相同的语法。如果名称和选择器匹配多个序列,则监控管道将确定如何将多个序列折叠为单个值。该选择器是累加的,并且不能选择描述 不是 目标对象(Pods 类型中的目标 Pod 和 Object 类型中描述的对象)的对象的指标。
基于与 Kubernetes 对象无关的指标进行自动伸缩
在 Kubernetes 上运行的应用程序可能需要根据与 Kubernetes 集群中任何对象没有明显关系的指标进行自动伸缩,例如描述与 Kubernetes 命名空间没有直接关联的托管服务的指标。在 Kubernetes 1.10 及更高版本中,您可以使用外部指标来解决此用例。
使用外部指标需要了解您的监控系统;设置类似于使用自定义指标时所需的设置。外部指标允许您根据监控系统中可用的任何指标自动伸缩您的集群。如上所述,提供带有 name 和 selector 的 metric 块,并使用 External 指标类型而不是 Object。如果 metricSelector 匹配多个时间序列,则 HorizontalPodAutoscaler 将使用其值的总和。外部指标同时支持 Value 和 AverageValue 目标类型,它们的功能与使用 Object 类型时完全相同。
例如,如果您的应用程序处理来自托管队列服务的任务,则可以将以下部分添加到 HorizontalPodAutoscaler 清单中,以指定每 30 个未完成的任务需要一个工作进程。
- type: External
external:
metric:
name: queue_messages_ready
selector:
matchLabels:
queue: "worker_tasks"
target:
type: AverageValue
averageValue: 30
如果可能,最好使用自定义指标目标类型而不是外部指标,因为集群管理员更容易保护自定义指标 API。外部指标 API 可能会允许访问任何指标,因此集群管理员在公开它时应谨慎。
附录:Horizontal Pod Autoscaler 状态条件
当使用 HorizontalPodAutoscaler 的 autoscaling/v2 形式时,您将能够看到 Kubernetes 在 HorizontalPodAutoscaler 上设置的状态条件。这些状态条件指示 HorizontalPodAutoscaler 是否能够进行伸缩,以及它当前是否受到任何限制。
条件显示在 status.conditions 字段中。要查看影响 HorizontalPodAutoscaler 的条件,我们可以使用 kubectl describe hpa
kubectl describe hpa cm-test
Name: cm-test
Namespace: prom
Labels: <none>
Annotations: <none>
CreationTimestamp: Fri, 16 Jun 2017 18:09:22 +0000
Reference: ReplicationController/cm-test
Metrics: ( current / target )
"http_requests" on pods: 66m / 500m
Min replicas: 1
Max replicas: 4
ReplicationController pods: 1 current / 1 desired
Conditions:
Type Status Reason Message
---- ------ ------ -------
AbleToScale True ReadyForNewScale the last scale time was sufficiently old as to warrant a new scale
ScalingActive True ValidMetricFound the HPA was able to successfully calculate a replica count from pods metric http_requests
ScalingLimited False DesiredWithinRange the desired replica count is within the acceptable range
Events:
对于此 HorizontalPodAutoscaler,您可以在正常状态下看到几个条件。第一个条件 AbleToScale 指示 HPA 是否能够获取和更新伸缩,以及是否有任何与退避相关的条件会阻止伸缩。第二个条件 ScalingActive 指示 HPA 是否已启用(即目标的副本计数不为零)并且能够计算所需的伸缩。当它为 False 时,通常表示获取指标时出现问题。最后,最后一个条件 ScalingLimited 表示所需的伸缩受到 HorizontalPodAutoscaler 的最大值或最小值的限制。这表明您可能希望提高或降低 HorizontalPodAutoscaler 上的最小或最大副本计数约束。
数量
HorizontalPodAutoscaler 和指标 API 中的所有指标都使用 Kubernetes 中称为数量的特殊整数表示法指定。例如,数量 10500m 在十进制表示法中将写为 10.5。指标 API 将在可能的情况下返回没有后缀的整数,否则通常会以毫单位返回数量。这意味着当以十进制表示法书写时,您可能会看到指标值在 1 和 1500m 或 1 和 1.5 之间波动。
其他可能的情况
以声明方式创建自动伸缩器
我们可以使用以下清单以声明方式创建 HorizontalPodAutoscaler,而不是使用 kubectl autoscale 命令以命令方式创建它:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: php-apache
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: php-apache
minReplicas: 1
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
然后,通过执行以下命令创建自动伸缩器:
kubectl create -f https://k8s.io/examples/application/hpa/php-apache.yaml
horizontalpodautoscaler.autoscaling/php-apache created