Autoscaling based on only CPU and memory can be insufficient for complex scenarios. To use custom metrics and external metrics from Prometheus for HPA, this topic shows you how to retrieve monitoring data and configure autoscaling. This provides a more flexible scaling mechanism for your applications.
Prerequisites
-
Alibaba Cloud Managed Service for Prometheus is deployed. For more information, see Connect to and configure Alibaba Cloud Managed Service for Prometheus.
-
The ack-alibaba-cloud-metrics-adapter component is deployed. For more information, see Deploy the ack-alibaba-cloud-metrics-adapter component.
NoteYou can log on to the ACK console and deploy the ack-alibaba-cloud-metrics-adapter component from the page.
How it works
By default, HPA only supports autoscaling based on CPU and memory, which can be insufficient for many operational needs. Alibaba Cloud Managed Service for Prometheus is fully compatible with the open source Prometheus ecosystem. It supports monitoring for a wide range of components, provides various out-of-the-box dashboards, and offers a fully managed Prometheus service. The process involves three main steps:
-
Expose monitoring metrics in an ACK cluster by using Alibaba Cloud Managed Service for Prometheus.
-
The ack-alibaba-cloud-metrics-adapter component is responsible for converting Prometheus monitoring metrics into Kubernetes aggregated metrics that are consumable by HPA. For more information, see Autoscaling on multiple metrics and custom metrics.
-
Configure and deploy an HPA to scale based on the metrics from the previous step.
Metrics are categorized into two types:
-
Custom Metric: Scales based on metrics related to a target Kubernetes object, such as a Pod. An example is a metric specific to the Pod itself. For more information, see autoscaling-on-multiple-metrics-and-custom-metrics.
-
External Metric: Scales based on metrics that are not related to the target Kubernetes object, such as a Pod. For example, you can scale the Pods of a workload based on the overall business QPS metric. For more information, see autoscaling-on-metrics-not-related-to-kubernetes-objects.
-
This topic describes how to configure ack-alibaba-cloud-metrics-adapter to convert metrics from Alibaba Cloud Managed Service for Prometheus into HPA-compatible metrics and implement autoscaling based on these metrics.
Step 1: Get Prometheus monitoring data
Example 1: Use default ACK metrics
You can use the default metrics from Alibaba Cloud Managed Service for Prometheus, which is installed by default in ACK, for horizontal pod autoscaling. Supported metrics include cAdvisor container metrics, Node-Exporter basic node monitoring metrics, GPU-Exporter metrics, and any other metrics you have integrated with Alibaba Cloud Managed Service for Prometheus. To view the integrated metrics:
Log on to the ACK console. In the left navigation pane, click Clusters.
On the Clusters page, click the name of your cluster. In the left navigation pane, click .
-
In the upper-right corner, click Go to ARMS Prometheus.
-
In the left-side navigation pane of the Application Real-Time Monitoring Service (ARMS) console, click Settings to view all metrics integrated with Alibaba Cloud Managed Service for Prometheus.
Example 2: Use pod-reported metrics
This example deploys a sample application that exposes metrics in the standard Prometheus format, such as the http_requests_total metric, which indicates the number of visits. For more information, see metric_type.
-
Deploy the application workload.
Log on to the ACK console. In the left navigation pane, click Clusters.
-
On the Clusters page, click the name of the target cluster. In the left-side navigation pane, click .
-
On the Deployments page, click Create from YAML in the upper-right corner. On the Create page, select Custom from the Sample Template drop-down list, enter the following YAML, and click Create.
-
Add a ServiceMonitor.
-
Log on to the Application Real-Time Monitoring Service (ARMS) console.
-
In the left-side navigation pane, click Integration Management. On the Integrated Environments page, on the Container Environment tab, select the region where your cluster is located, and then click the environment name that matches your cluster name.
-
On the container environment page, click the Metric Scraping tab. In the left-side navigation pane, click ServiceMonitor. On the ServiceMonitor page, click Create. In the Add ServiceMonitor Configuration panel, click YAML Edit, add the following ServiceMonitor configuration, and then create the ServiceMonitor.
apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: annotations: arms.prometheus.io/discovery: 'true' name: sample-app namespace: default spec: endpoints: - interval: 30s port: http path: /metrics namespaceSelector: any: true selector: matchLabels: app: sample-app
-
-
Verify the monitoring status.
Click the Self-Monitoring tab. In the Targets section, if default/sample-app/0(1/1 up) is displayed, the application is successfully monitored by Alibaba Cloud Managed Service for Prometheus.
-
On the Prometheus dashboard, query the value of
http_requests_totalfor a recent time range to confirm that monitoring data is being collected correctly.
Step 2: Configure the ack-alibaba-cloud-metrics-adapter component
Log on to the ACK console. In the left navigation pane, click Clusters.
-
On the Clusters page, click the name of the target cluster. In the left-side navigation pane, click .
-
On the Helm page, find ack-alibaba-cloud-metrics-adapter and click Update in the Actions column.
-
In the Update Release panel, configure the following YAML, and then click OK.
The following table describes some of the fields. For a detailed description of the ack-alibaba-cloud-adapter configuration file, see ack-alibaba-cloud-metrics-adapter component configuration reference.
Parameter
Description
AlibabaCloudMetricsAdapter. prometheus.adapter.rules.customModify the value of this field to match the content in the example YAML.
alibabaCloudMetricsAdapter. prometheus.urlThe URL of your Alibaba Cloud Managed Service for Prometheus instance. For information about how to obtain the Prometheus data request URL, see How to obtain the Prometheus data request URL.
AlibabaCloudMetricsAdapter. prometheus.prometheusHeader[].AuthorizationThe authentication information. For more information, see How to obtain the Prometheus data request URL.
-
Prometheus V1: Authentication is not required by default. If token authentication is enabled, you need to configure this field.
Prometheus V2: Authentication is enabled by default. If password-free access is not enabled, you need to configure this field.
AlibabaCloudMetricsAdapter. prometheus.adapter.rules.defaultSpecifies whether to create predefined metrics. We recommend that you disable this by setting the value to
false. -
After configuring and deploying the component, run the following commands to verify that the Kubernetes aggregation API is receiving data.
Custom metrics
-
Use a custom metrics query to view the details and list of available HPA metrics.
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/" | jq . -
Query the current values of the
container_memory_working_set_bytes_per_secondandcontainer_cpu_usage_core_per_secondmetrics in the kube-system namespace.# Query container_memory_working_set_bytes_per_second to view the current working memory size per second for Pods in the kube-system namespace. kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/kube-system/pods/*/container_memory_working_set_bytes_per_second" | jq . # Query container_cpu_usage_core_per_second to view the CPU core usage per second for Pods in the kube-system namespace. kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1/namespaces/kube-system/pods/*/container_cpu_usage_core_per_second" | jq .Sample output:
{ "kind": "MetricValueList", "apiVersion": "custom.metrics.k8s.io/v1beta1", "metadata": { "selfLink": "/apis/custom.metrics.k8s.io/v1beta1/namespaces/kube-system/pods/%2A/container_cpu_usage_core_per_second" }, "items": [ { "describedObject": { "kind": "Pod", "namespace": "kube-system", "name": "ack-cost-exporter-7f44d55c66-cgtz7", "apiVersion": "/v1" }, "metricName": "container_cpu_usage_core_per_second", "timestamp": "2025-12-30T03:30:21Z", "value": "4m", "selector": null }
External metrics
-
Use an external metrics query to view the details and list of available external HPA metrics.
kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/" | jq . -
Query the current value of the
http_requests_per_secondmetric in the default namespace.kubectl get --raw "/apis/external.metrics.k8s.io/v1beta1/namespaces/default/http_requests_per_second" | jq .Sample output:
{ "kind": "ExternalMetricValueList", "apiVersion": "external.metrics.k8s.io/v1beta1", "metadata": {}, "items": [ { "metricName": "http_requests_per_second", "metricLabels": {}, "timestamp": "2025-12-30T03:29:40Z", "value": "328m" } ] }
Step 3: Configure and deploy the HPA
You can expose Prometheus metrics as either custom metrics or external metrics. The following sections describe how to use both methods for HPA scaling.
Custom metrics
-
Create an hpa.yaml file.
kind: HorizontalPodAutoscaler apiVersion: autoscaling/v2 metadata: name: sample-app-memory-high spec: # The scaling target for the HPA. The HPA dynamically modifies the number of Pods for this object. scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: sample-app # The minimum and maximum number of Pods for the HPA. minReplicas: 1 maxReplicas: 10 # An array of metrics to monitor. Multiple metric types are supported. metrics: - type: Pods pods: # Metric to use: pods/container_memory_working_set_bytes_per_second. metric: name: container_memory_working_set_bytes_per_second # The target value is of the AverageValue type. For the Pods metric type, only AverageValue is supported as the target. target: type: AverageValue averageValue: 1024000m # Here, 1024000m represents a memory threshold of 1 KB. The unit of the metric is bytes per second. 'm' is a Kubernetes precision unit. When decimal values require high precision, Kubernetes uses units like 'm' or 'k'. For example, 1001m=1.001 and 1k=1000. -
Create the HPA application.
kubectl apply -f hpa.yaml -
After enabling load balancing for the Service, run the following command to perform a stress test.
Replace
<EXTERNAL-IP>with the actual LoadBalancer external IP address or domain name of the sample-app Service.ab -c 50 -n 2000 http://<EXTERNAL-IP>:8080/ -
Run the following command to view HPA details:
kubectl get hpa sample-app-memory-highExpected output:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE sample-app-memory-high Deployment/sample-app 40886272/1024 1 10 1 22s
External metrics
-
Create an hpa.yaml file.
apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: sample-app spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: sample-app minReplicas: 1 maxReplicas: 10 metrics: - type: External external: metric: name: http_requests_per_second selector: matchLabels: job: "sample-app" # For the External metric type, only Value and AverageValue are supported as the target types. target: type: AverageValue averageValue: 500m -
Create the HPA application.
kubectl apply -f hpa.yaml -
After enabling load balancing for the Service, run the following command to perform a stress test.
Replace
<EXTERNAL-IP>with the actual LoadBalancer external IP address or domain name of the sample-app Service.ab -c 50 -n 2000 http://<EXTERNAL-IP>:8080/ -
Run the following command to view HPA details:
kubectl get hpa sample-appExpected output:
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE sample-app Deployment/sample-app 33m/500m 1 10 1 7m
ack-alibaba-cloud-metrics-adapter configuration
The ack-alibaba-cloud-metrics-adapter component converts Prometheus metrics into HPA-compatible metrics in four steps:
-
Discovery: The ack-alibaba-cloud-metric-adapter discovers available metrics from Prometheus.
-
Association: Associates the metrics with Kubernetes resources such as Pods, Nodes, and namespaces.
-
Naming: Defines the names of the converted metrics for HPA to reference.
-
Querying: Defines how to query metric data from Prometheus.
For example, the following configuration converts the http_requests_total metric from the sample-app container into http_requests_per_second for HPA:
- seriesQuery: http_requests_total{namespace!="",pod!=""}
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: ^(.*)_total
as: ${1}_per_second
metricsQuery: sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)
|
Parameter |
Description |
|
|
The PromQL expression to request data. |
|
|
Performs an aggregation operation on the data requested by the PromQL expression in seriesQuery. Note
The |
|
|
Matches a PromQL data label with a Kubernetes |
|
|
Uses a regular expression to convert a Prometheus metric name into a more readable name for HPA. This example converts |
-
Discovery
Specify the Prometheus metric to be converted. You can use
seriesFiltersto precisely filter metrics.seriesQuerycan search by labels. Sample code:seriesQuery: http_requests_total{namespace!="",pod!=""} seriesFilters: - isNot: "^container_.*_seconds_total"seriesFiltersis optional and is used to filter metrics:-
is:<regex>: Matches metrics that contain the regular expression. -
isNot:<regex>: Matches metrics that do not contain the regular expression.
-
-
Association
Set the mapping between Prometheus metric labels and Kubernetes resources. The labels for the
http_requests_totalmetric includenamespace!=""andpod!="".- seriesQuery: http_requests_total{namespace!="",pod!=""} resources: overrides: namespace: {resource: "namespace"} pod: {resource: "pod"} -
Naming
Converts the Prometheus metric name to an HPA metric name, but does not change the Prometheus metric name itself. If you use the original Prometheus metric, you do not need to configure this.
You can run the command
kubectl get --raw "/apis/custom.metrics.k8s.io/v1beta1"to view all available HPA metrics.- seriesQuery: http_requests_total{namespace!="",pod!=""} resources: overrides: namespace: {resource: "namespace"} pod: {resource: "pod"} name: matches: "^(.*)_total" as: "${1}_per_second" -
Querying
A template for querying the Prometheus API. The ack-alibaba-cloud-adapter component populates this template with parameters from the HPA, sends a request to the Prometheus API, and provides the returned value to the HPA for scaling.
- seriesQuery: http_requests_total{namespace!="",pod!=""} resources: overrides: namespace: {resource: "namespace"} pod: {resource: "pod"} name: matches: ^(.*)_total as: "${1}_per_second" metricsQuery: sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)
Prometheus data request URL
Scenario 1: Alibaba Cloud Prometheus
Log on to the ACK console. In the left navigation pane, click Clusters.
On the Clusters page, click the name of your cluster. In the left navigation pane, click .
-
In the upper-right corner, click Go to ARMS Prometheus. In the left-side navigation pane of the Application Real-Time Monitoring Service (ARMS) console, click Settings, then click the Settings tab to get the HTTP API Address (Grafana Read Address).
We recommend that you use the internal network URL. If the internal network is not accessible, you can use the public network URL.
To enhance data read security, click Generate token to create a token. You must then include this token in your HTTP API calls for authentication.
-
Create Prometheus authentication information.
-
Prometheus V1: If token authentication is enabled, configure the token directly in the component configuration.
On the HTTP API Address (Grafana Read Address) page, find the Token field and click the copy icon to get the token value.
... prometheus: prometheusHeader: - Authorization: {Token} ... -
Prometheus V2: AccessKey-based authentication is enabled by default. If you have not enabled password-free access in the Prometheus console, you must Base64-encode your AccessKey and AccessSecret, then enter the result into the ack-alibaba-cloud-metrics-adapter component configuration.
-
Generate a Base64-encoded string.
Concatenate your AccessKey ID and AccessKey secret in the
AccessKey:AccessSecretformat and perform Base64 encoding.echo -n 'accessKey:secretKey' | base64 -
Configure the component by entering the generated string in the
Basic <encoded_string>format into theAuthorizationfield ofprometheusHeader.... prometheus: prometheusHeader: - Authorization: Basic YWxxxxeQ== ...
-
-
Scenario 2: Open source Prometheus
For a self-managed open source Prometheus setup, you must expose the standard Prometheus access API through a Service and configure its URL in the metrics-adapter component. This configures HPA to use your open source Prometheus instance as a data source.
This example uses the ack-prometheus-operator community edition Helm chart from the ACK Marketplace. For more information, see open source Prometheus.
-
Deploy the Prometheus monitoring solution and expose the standard Prometheus API.
Log on to the ACK console. In the left navigation pane, click .
-
On the Marketplace page, search for and click ack-prometheus-operator, then click Quick Deployment in the upper-right corner.
-
On the creation page, select the Cluster and Namespace, modify the Release Name as needed, and then click Next. Modify the Parameters as needed, and then click OK.
-
Check the deployment result.
-
Expose the standard Prometheus API via a Service. This example uses the ack-prometheus-operator Service named ack-prometheus-operator-prometheus.
-
Access ServiceIP:9090 in a browser. To enable public access, expose the Service through a Server Load Balancer (SLB) instance to view the Prometheus console.
-
In the top menu bar, click Status > Targets to view all scrape jobs.
If the status of all jobs is UP, all scrape jobs are running as expected.
The page displays scrape job groups such as alertmanager-main (3/3 up) and apiserver (3/3 up), with the State of all jobs being UP (green).
-
-
Check the corresponding service and namespace in the Labels.
This example uses the ServiceName 'ack-prometheus-operator-prometheus' and the ServiceNamespace 'monitoring' to illustrate the URL for this open source Prometheus data request.
http://ack-prometheus-operator-prometheus.monitoring.svc.cluster.local:9090
-
Configure the Prometheus data source URL parameter in the component to ensure the component can communicate with Prometheus.
If you choose to access the standard Prometheus API over the public network, you can configure it as shown in the following example.
AlibabaCloudMetricsAdapter: ...... prometheus: enabled: true url: http://your_domain.com:9090 # Replace your_domain.com with your public IP address.For the ack-prometheus-operator solution, the
urlvalue would behttp://ack-prometheus-operator-prometheus.monitoring.svc.cluster.local:9090.
For more information about how to obtain Prometheus data, see Add Prometheus as a data source in Grafana.
Related topics
-
To implement HPA by using external metrics such as HTTP request rate or Ingress QPS, see Horizontal pod autoscaling based on Nginx Ingress component metrics.
-
To use Nginx Ingress to autoscale multiple applications and dynamically adjust Pod replica counts based on application load, see Horizontally scale multiple applications based on Nginx Ingress traffic metrics.