HPA & metrics-server
Autoscale a Deployment on CPU usage.
By Invicly Tech, , in Kubernetes Administrator (CKA). About 9 minutes to read.
In short
The HorizontalPodAutoscaler changes a workload's replica count to keep a metric near a target, most often CPU utilization. It reads metrics from metrics-server, which collects usage from kubelets. CPU-based scaling only works when containers set CPU requests.
Explained simply
Traffic changes during the day. At night two copies of your app might be enough; at lunch you might need ten. The HorizontalPodAutoscaler (HPA) watches how busy your Pods are and changes the number of copies for you.
It needs numbers to work with. Those come from metrics-server, a small add-on that asks each node's kubelet how much CPU and memory every Pod is using. Without metrics-server, the HPA is blind and does nothing.
You give the HPA a target, such as "keep average CPU at 50 percent of what the Pods requested". If Pods run hotter, it adds replicas. If they are idle for a while, it removes some, but never below your minimum or above your maximum.
Horizontal means more copies. There is also vertical scaling (the VerticalPodAutoscaler), which gives each copy more CPU or memory instead. The CKA focuses on the HPA.
Press Play on a diagram to walk through it one step at a time.
- 1Collect metrics
metrics-server scrapes kubelets for Pod usage.
- 2Compare to target
Usage as percent of requests vs target, e.g. 50%.
- 3Compute replicas
desired = ceil(current x actual / target).
- 4Scale workload
Updates replicas within min and max.
- 5Stabilize
Scale-down waits a 5-minute window by default.
- Back to step 1
- metrics-server to kubelet (cAdvisor): Scrape Pod CPU and memory, every 15s1Scrape Pod CPU and memory, every 15s
- HPA controller to metrics-server: GET metrics.k8s.io via API server2GET metrics.k8s.io via API server
- metrics-server to HPA controller: Usage per Pod3Usage per Pod
- 4Compare with requests and targetHPA controller to HPA controller: Compare with requests and target
- HPA controller to Deployment: Update scale subresource: replicas5Update scale subresource: replicas
In depth
Installing and checking metrics-server
metrics-server is not part of a kubeadm cluster by default. Install it from its release manifest: kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml. It registers the API group metrics.k8s.io through an APIService, which is what kubectl top and the HPA read.
In lab clusters the kubelet often uses a self-signed serving certificate, so metrics-server logs x509 errors and stays not Ready. The usual lab fix is adding --kubelet-insecure-tls to its container args. Never do that in production; sign kubelet certificates properly instead. By default it collects every 15 seconds, so give it a minute before expecting numbers.
- kubectl get apiservice v1beta1.metrics.k8s.io should say True
- kubectl -n kube-system logs deploy/metrics-server for errors
- kubectl top nodes proves the pipeline works end to end
The algorithm and its safety margins
Every 15 seconds the HPA controller computes desiredReplicas = ceil(currentReplicas x currentMetric / targetMetric). Utilization is averaged over Pods and measured against requests, so a Pod requesting 200m and using 100m is at 50 percent.
Several rules stop it from flapping. If the ratio is within 10 percent of 1.0 (the tolerance), it does nothing. Pods that are not yet Ready or have no metrics are treated conservatively, so a slow-starting app does not trigger runaway scale-up. With several metrics, the HPA computes a count for each and takes the largest. Scale-down uses a stabilization window of 300 seconds: it picks the highest recommendation from the last 5 minutes, so short dips do not remove Pods.
- 13 Pods, request 200m
Target 50 percent utilization
- 2Average use 180m
180 / 200 = 90 percent
- 3Ratio 90 / 50 = 1.8
Outside the 10 percent tolerance
- 4ceil(3 x 1.8) = 6
Within min 2 and max 10
- 5Scale to 6
Deployment replicas set to 6
Shaping behaviour with the behavior field
autoscaling/v2 adds spec.behavior with separate scaleUp and scaleDown sections. Each has a stabilizationWindowSeconds and a list of policies such as type Pods value 4 periodSeconds 60 (at most 4 Pods per minute) or type Percent value 50. selectPolicy chooses Max (the default) or Min among policies, or Disabled to turn that direction off.
The defaults are sensible: scale-up may double the Pods or add 4 per 15 seconds, whichever is more, with no window; scale-down may remove everything above minimum per 15 seconds but only after the 300 second window. Slow down scale-down for apps with expensive warm-up; speed up scale-up for spiky traffic.
Living with an HPA
Once an HPA owns a Deployment, it writes spec.replicas. If your CI pipeline or GitOps tool also applies a replicas value, the two will fight and Pods will jump up and down. Remove replicas from the manifest after enabling the HPA.
Memory is a weaker scaling signal than CPU, because many runtimes do not give memory back after a spike, so the HPA may scale up and never down. kubectl describe hpa shows the current metrics, the conditions AbleToScale, ScalingActive and ScalingLimited, and recent scaling events with reasons, which is the first place to look when it behaves oddly.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Install metrics-server~40m
- 2Create an HPA on CPU~40m
- 3Generate load and watch scaling~40m
Key points
- Install metrics-server first; kubectl top proves it works.
- Utilization is measured against requests, so Pods need CPU requests.
- autoscaling/v2 supports CPU, memory, custom and external metrics.
- TARGETS showing unknown usually means missing metrics or requests.
Key terms
Tap a card to flip it. 0/5 known
Examples
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: web }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: web }
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 50 }
# kubectl get hpa web --watchAutoscale and load-test a web app
Step 1: create a Deployment with a CPU request and a Service. Step 2: create the HPA with kubectl autoscale. Step 3: start a busy loop that calls the Service. Step 4: in another terminal watch the HPA; TARGETS climbs above 50 percent and REPLICAS goes up. Step 5: delete the load Pod; after about 5 minutes replicas drop back to the minimum.
kubectl create deploy php --image=registry.k8s.io/hpa-example --port=80
kubectl set resources deploy php --requests=cpu=200m
kubectl expose deploy php --port=80
kubectl autoscale deploy php --cpu-percent=50 --min=1 --max=10
kubectl run load --image=busybox:1.36 --restart=Never -- \
/bin/sh -c 'while true; do wget -q -O- http://php; done'
kubectl get hpa php --watch
kubectl delete pod loadFixing TARGETS unknown
kubectl get hpa shows cpu: unknown/50% (shown in angle brackets). Step 1: run kubectl top pods; if it errors, metrics-server is the problem, so check its Pod and logs. Step 2: if top works, check that every container in the target Pods has a CPU request; describe hpa says failed to get cpu utilization: missing request for cpu. Step 3: add the request; new Pods roll out and TARGETS shows a real number within a minute.
kubectl describe hpa web | grep -A3 Conditions
kubectl top pods
kubectl -n kube-system get pods -l k8s-app=metrics-server
kubectl get deploy web -o jsonpath='{.spec.template.spec.containers[*].resources}'
kubectl set resources deploy web --requests=cpu=100mQuick reference
- kubectl autoscale deploy web --cpu-percent=50 --min=2 --max=10
- desired = ceil(current replicas x current metric / target metric)
- No scaling if the ratio is within 10 percent of the target (tolerance 0.1)
- Scale-down waits a 300 second stabilization window by default
- Lab fix for metrics-server x509 errors: add --kubelet-insecure-tls to its args
- Several metrics: the HPA uses whichever needs the most replicas
- Remove spec.replicas from manifests once an HPA manages the Deployment
Common mistakes
- Creating an HPA for Pods without CPU requests; it cannot compute utilization.
- Also setting replicas in the Deployment via CI, fighting the HPA.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Check whether metrics-server works in your cluster and list the three Pods using the most memory in all namespaces.
- Exercise 2medium
Create an autoscaling/v2 HPA named api for Deployment api: min 2, max 8, target 70% CPU, and scale-down no faster than 1 Pod per minute.
- Exercise 3hard
On a kubeadm lab where kubectl top fails with x509 errors, install metrics-server and make it work, then show an HPA reading real numbers.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why does my HPA say unknown?
- Either metrics-server is not running or not reachable, or the target Pods have no CPU request. kubectl describe hpa states which one in its conditions.
- Can the HPA scale to zero?
- Not by default: minReplicas must be at least 1 unless an alpha feature gate is enabled. Tools like KEDA are used when you need scale to zero.
- Should I use HPA and VPA together?
- Not on the same CPU or memory metric, because they would fight. A common pattern is VPA in recommendation-only mode to tune requests, and HPA to change the replica count.