Capstone: Autoscale an App on Kubernetes with HPA
Your app from the earlier labs runs a fixed number of pods: flat out at lunchtime, idle at night, and nobody can run kubectl scale by hand all day. This capstone shows how to autoscale an app on Kubernetes with HPA, the Horizontal Pod Autoscaler: install its metrics, set a target, then load the app on your kind cluster and watch pods come and go.
What the Horizontal Pod Autoscaler does
The Horizontal Pod Autoscaler (HPA) is a Kubernetes object that changes a Deployment's replica count to follow a metric, a measured number such as average CPU use. Horizontal means more or fewer pods; giving each pod more CPU would be vertical scaling. You set a target, a minimum and a maximum number of replicas.
For CPU, the target is a utilisation: CPU use as a percentage of the CPU request from lesson 15, the amount the scheduler reserves. A pod that requests 100m, a tenth of a core, and uses 50m is at 50%. Use can pass the request, up to the limit, so 300m is 300%. The HPA averages this over all the Deployment's pods.
The numbers come from metrics-server, an add-on that collects every container's CPU and memory use from the kubelets every 15 seconds and serves the latest values as the Metrics API, metrics.k8s.io. The HPA and kubectl top both read it. It keeps no history, so it is not a monitoring system.
The HPA's controller is one more control loop in kube-controller-manager, from lesson 8. In the flowchart, notice that it never starts a pod: every 15 seconds it may change the Deployment's replicas, and the Deployment, scheduler and kubelet do the rest, as after kubectl scale in lesson 18.
The formula: how many replicas to ask for
On each check, the HPA picks a replica count with one formula from the Kubernetes documentation:
desiredReplicas = ceil( currentReplicas × currentMetricValue / targetMetricValue )
ceil means round up. For example, two pods averaging 90% against a 50% target give 2 × 90 / 50 = 3.6, so the HPA asks for 4.
Then three rules apply. If current divided by target is between 0.9 and 1.1, within the default 10% tolerance, nothing changes. The result stays between the minimum and maximum. And by default, each 15-second period may at most double the pods or add four, whichever is more.
Prerequisites: metrics-server and CPU requests
The lab folder course-labs/containers-and-kubernetes-fundamentals/06-hpa holds four files. Use the cluster from lesson 17, with the context kind-lab and earlier labs cleaned up. In the seven-step diagram, notice that you only add and remove load: the HPA does all the scaling.
metrics-server.yaml is metrics-server v0.9.1's official manifest plus one line. metrics-server reads each kubelet over HTTPS and checks its certificate, the signed proof of identity from lesson 12. kind's kubelets use self-signed certificates, which the cluster's certificate authority never signed, so the check fails. The added flag skips it:
- name: metrics-server
image: registry.k8s.io/metrics-server/metrics-server:v0.9.1
args:
...
- --metric-resolution=15s
- --kubelet-insecure-tls
Use the flag on test clusters only. Without it, the metrics-server pod stays 0/1 ready, and kubectl -n kube-system logs deploy/metrics-server shows x509: cannot validate certificate for 172.18.0.2 because it doesn't contain any IP SANs, with your node's address.
app.yaml runs cpu-app, a tiny Python web server kept in a ConfigMap that does a burst of maths per request, so requests cost CPU. Its container sets a CPU request; without one, utilisation is undefined and the HPA does nothing for CPU. Trimmed:
- name: app
image: python:3.14-alpine
resources:
requests:
cpu: 100m
memory: 32Mi
limits:
cpu: 500m
memory: 128Mi
With the 500m limit, one busy pod can reach 500%. There is no replicas line, so the Deployment starts with the default of one pod. Once an HPA manages it, a replicas value in your file would reset the count at every apply.
Create the HPA and add load
hpa.yaml is the autoscaler itself. It names the Deployment to scale in scaleTargetRef and asks for 50% average CPU utilisation, with 1 to 5 replicas:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: cpu-app
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: cpu-app
minReplicas: 1
maxReplicas: 5
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
Recent kubectl can also create the same object from the command line, with kubectl autoscale deployment cpu-app --cpu=50% --min=1 --max=5. From the 06-hpa folder, apply the first three files:
kubectl apply -f metrics-server.yaml -f app.yaml -f hpa.yaml
You should see thirteen created lines, the last one horizontalpodautoscaler.autoscaling/cpu-app created. After a minute, kubectl top pods shows the pod's CPU, such as 1m; error: Metrics API not available means wait longer. Then kubectl get hpa should show REPLICAS 1 and TARGETS cpu: 0%/50%, current over target utilisation. kubectl before 1.30 leaves out cpu:. cpu: <unknown>/50% means no metrics yet: metrics-server is not ready, or the pods lack a CPU request.
load.yaml is a busybox pod that requests http://cpu-app in an endless loop, 10 milliseconds apart. Start it and watch; -w, short for --watch, prints a new row whenever the HPA changes:
kubectl apply -f load.yaml
kubectl get hpa -w
You should see pod/load created, then rows like these within a minute or two (trimmed; the percentages are illustrative):
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
cpu-app Deployment/cpu-app cpu: 180%/50% 1 5 1 2m30s
cpu-app Deployment/cpu-app cpu: 140%/50% 1 5 4 2m45s
cpu-app Deployment/cpu-app cpu: 120%/50% 1 5 5 3m15s
REPLICAS climbs to 5 in one or two steps and stops there, because maxReplicas caps it, so TARGETS can stay above 50%. Press Ctrl+C. kubectl get pods lists five cpu-app pods; one stuck in Pending means the node has no CPU left for its request, as in lesson 20.
In the graph, notice the two speeds: replicas rise within a minute of the load, but stay at 5 long after the CPU drops.
Scale-down is slow on purpose
Stop the load, then watch again:
kubectl delete -f load.yaml
kubectl get hpa -w
You should see pod "load" deleted from default namespace. Within a minute or so, TARGETS falls to cpu: 0%/50%, yet REPLICAS stays at 5 for about five minutes more. That is the stabilisation window: before scaling down, the HPA uses the highest count it calculated in the last 300 seconds, by default.
The window prevents flapping, the replica count bouncing up and down as the metric wobbles: otherwise a short lull would remove pods a returning rush needs. Scale-up has no window by default. When the window ends, the default policy may remove every extra pod at once, down to minReplicas, so REPLICAS drops straight to 1.
kubectl describe hpa cpu-app lists each change under Events, such as New size: 1; reason: All metrics below target. Always delete the load generator first: left running, it keeps your laptop busy. Then remove the rest:
kubectl delete -f hpa.yaml -f app.yaml -f metrics-server.yaml
You should see one deleted line per object. That was the last lab: kind delete cluster --name lab removes the cluster.
Check yourself
Four pods average 75% CPU against a 50% target, with maxReplicas: 5. What replica count does the HPA set?
Five. The formula asks for 4 × 75 / 50 = 6, but the maximum caps it, so TARGETS stays above 50% until the load drops.
You remove the resources block from app.yaml. What does kubectl get hpa show under load, and why?
cpu: <unknown>/50%, and nothing scales. Utilisation is CPU use divided by the request, so with no request there is nothing to compare against.
After the load stops, TARGETS shows 0% but REPLICAS stays at 5 for minutes. Is the HPA broken?
No. The stabilisation window makes it use the highest count calculated in the last five minutes, so a short lull does not remove pods a returning rush needs.
Go deeper
- Capacity Planning in the Cloud Era: the HPA only adds pods your nodes have room for; plan that headroom.
- Setup Kubernetes cluster monitoring the easy way: metrics-server keeps no history; a Prometheus and Grafana stack does, to tune targets later.