Scaling by hand and automatically

More copies when busy, fewer when quiet.

Beginner30 min · lesson 9 of 21
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (3 files, 1 KB): scaling.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/k8s-fund/scaling.tar.gz && tar -xzf scaling.tar.gz, which creates ~/lab/scaling/. SHA-256: 7a00ae4505868949fcea4ba4287467e64dd7ce22235950a2ac1784d2ca844dfb

A shop is quiet at night and busy at lunch. A news site gets ten times its usual traffic when a story breaks. Run enough copies for the peak all day and you pay for idle machines. Run too few and the site slows down exactly when people are watching.

Changing the number of copies by hand takes one command. Letting Kubernetes change it for you, based on how busy the Pods are, takes an add-on and one more object. Plan about fifteen minutes for this lesson, most of it waiting for the autoscaler.

Scaling by hand

This file is a Deployment with one nginx Pod plus a Service called web, like the one in lesson 8, Services. Note the resources section: the Pod asks for 50 millicores of CPU, a twentieth of a core. The autoscaler later measures CPU use against that request.

web.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 1
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.30.6-alpine
resources:
requests:
cpu: 50m
limits:
cpu: 200m
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
ports:
- port: 80
ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl apply -f web.yaml && kubectl rollout status deployment/web
deployment.apps/web created service/web created Waiting for deployment "web" rollout to finish: 0 out of 1 new replicas have been updated... Waiting for deployment "web" rollout to finish: 0 of 1 updated replicas are available... deployment "web" successfully rolled out
$ kubectl scale deployment web --replicas=4 && kubectl rollout status deployment/web && kubectl get pods -l app=web
deployment.apps/web scaled Waiting for deployment "web" rollout to finish: 1 of 4 updated replicas are available... Waiting for deployment "web" rollout to finish: 2 of 4 updated replicas are available... Waiting for deployment "web" rollout to finish: 3 of 4 updated replicas are available... deployment "web" successfully rolled out NAME READY STATUS RESTARTS AGE web-7fcc4c77f4-9s2s8 1/1 Running 0 2s web-7fcc4c77f4-f9jp7 1/1 Running 0 2s web-7fcc4c77f4-jfvcg 1/1 Running 0 2s web-7fcc4c77f4-wmt67 1/1 Running 0 5s
$ kubectl scale deployment web --replicas=1 && kubectl rollout status deployment/web && kubectl get deployment web
deployment.apps/web scaled deployment "web" successfully rolled out NAME READY UP-TO-DATE AVAILABLE AGE web 1/1 1 1 5s

kubectl scale changes replicas on the Deployment, and the ReplicaSet does the rest. Three new Pods appeared next to the original, a few seconds old, and scaling back to 1 removed three of them straight away. That is all manual scaling is. The catch is that someone has to decide when.

Measuring: metrics-server

To scale on load, the cluster must know the load. A fresh cluster does not:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl top nodes
error: Metrics API not available

kubectl top and the autoscaler read the Metrics API, and nothing provides it yet. metrics-server is the standard add-on that does. It asks every kubelet for CPU and memory use every 15 seconds and keeps only the latest values. Install the newest release, v0.9.1, from its pinned URL:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml
serviceaccount/metrics-server created clusterrole.rbac.authorization.k8s.io/system:aggregated-metrics-reader created clusterrole.rbac.authorization.k8s.io/system:metrics-server created rolebinding.rbac.authorization.k8s.io/metrics-server-auth-reader created clusterrolebinding.rbac.authorization.k8s.io/metrics-server:system:auth-delegator created clusterrolebinding.rbac.authorization.k8s.io/system:metrics-server created service/metrics-server created deployment.apps/metrics-server created apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io created
$ kubectl -n kube-system rollout status deployment/metrics-server --timeout=90s
Waiting for deployment "metrics-server" rollout to finish: 0 of 1 updated replicas are available... error: timed out waiting for the condition
$ kubectl -n kube-system logs deployment/metrics-server | grep -m 2 x509
E1111 08:52:12.222028 1 scraper.go:149] "Failed to scrape node" err="Get \"https://172.18.0.3:10250/metrics/resource\": tls: failed to verify certificate: x509: cannot validate certificate for 172.18.0.3 because it doesn't contain any IP SANs" node="lab-worker2" E1111 08:52:12.225204 1 scraper.go:149] "Failed to scrape node" err="Get \"https://172.18.0.4:10250/metrics/resource\": tls: failed to verify certificate: x509: cannot validate certificate for 172.18.0.4 because it doesn't contain any IP SANs" node="lab-worker"

The install created nine objects, including an APIService that plugs metrics.k8s.io into the API server. But the Pod never became ready. Its log says why: metrics-server connects to each kubelet over HTTPS and checks its certificate, and kind's kubelets use self-signed certificates that do not list the node's IP address (doesn't contain any IP SANs).

On a lab cluster the usual fix is the flag --kubelet-insecure-tls, which skips that check. kubectl patch with a JSON patch appends it to the container's argument list without editing the downloaded file. kubectl wait --for=condition=Available then waits until the API server reports the Metrics API as working:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl -n kube-system patch deployment metrics-server --type=json -p '[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
deployment.apps/metrics-server patched
$ kubectl -n kube-system rollout status deployment/metrics-server --timeout=180s && kubectl wait --for=condition=Available apiservice/v1beta1.metrics.k8s.io --timeout=120s
Waiting for deployment "metrics-server" rollout to finish: 1 old replicas are pending termination... Waiting for deployment "metrics-server" rollout to finish: 1 old replicas are pending termination... Waiting for deployment "metrics-server" rollout to finish: 1 old replicas are pending termination... deployment "metrics-server" successfully rolled out apiservice.apiregistration.k8s.io/v1beta1.metrics.k8s.io condition met
Watch out
--kubelet-insecure-tls turns off certificate checking between metrics-server and the kubelets. It is fine for kind on your own machine. On a real cluster, give the kubelets serving certificates signed by the cluster CA instead, which most managed clusters already do.

metrics-server needs a moment for its first readings. If kubectl top pods still prints an error, run it again until it prints a table:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl top nodes
NAME CPU(cores) CPU(%) MEMORY(bytes) MEMORY(%) lab-control-plane 568m 14% 690Mi 11% lab-worker 151m 3% 177Mi 3% lab-worker2 518m 12% 215Mi 3%
$ kubectl top pods
NAME CPU(cores) MEMORY(bytes) web-7fcc4c77f4-wmt67 0m 12Mi

The control-plane node uses the most CPU, because it runs the API server and etcd. The single web Pod uses 0m, nothing measurable, because nobody is sending it requests.

Autoscaling: the HorizontalPodAutoscaler

A HorizontalPodAutoscaler (HPA) watches a metric and changes replicas for you. This one keeps the web Deployment between 1 and 5 Pods and aims for an average CPU use of 50% of the request, which is 25 millicores per Pod. The behavior part keeps this lab short, and the section on scaling back explains it:

hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: web
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: web
minReplicas: 1
maxReplicas: 5
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50
behavior:
scaleDown:
stabilizationWindowSeconds: 60 # lab only; the default is 300

Apply it, and run kubectl get hpa web until the TARGETS column shows a percentage:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl apply -f hpa.yaml
horizontalpodautoscaler.autoscaling/web created
$ kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: 0%/50% 1 5 1 5s

cpu: 0%/50% is current use against the target. Now add load: two busybox Pods fetch the page over and over in a loop.

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl create deployment load --image=busybox:1.38.0 --replicas=2 -- sh -c 'while true; do wget -q -O /dev/null http://web; done' && kubectl rollout status deployment/load
deployment.apps/load created Waiting for deployment "load" rollout to finish: 0 of 2 updated replicas are available... Waiting for deployment "load" rollout to finish: 1 of 2 updated replicas are available... deployment "load" successfully rolled out

Check kubectl get hpa web every 15 seconds or so (or leave kubectl get hpa web --watch running, and stop it with Ctrl+C). Here the reading sat at 12% for about a minute and a half, because each reading passes from the kubelet to metrics-server to the HPA, and each step adds a delay. Then it jumped well above the target:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: 86%/50% 1 5 3 2m6s
$ kubectl get pods -l app=web
NAME READY STATUS RESTARTS AGE web-7fcc4c77f4-6grmc 1/1 Running 0 29s web-7fcc4c77f4-kldjt 1/1 Running 0 29s web-7fcc4c77f4-wmt67 1/1 Running 0 4m25s
$ kubectl describe hpa web | sed -n '/^Events:/,$p'
Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SuccessfulRescale 30s horizontal-pod-autoscaler New size: 3; reason: cpu resource utilization (percentage of request) above target

The HPA works out the Pod count as current Pods times current use divided by target. The jump was to 128%, so 1 x 128 / 50 = 2.56, rounded up to 3, and the event names the reason. Two new Pods joined the original. With three Pods sharing the load, the average fell to 86%, still above target, so the HPA kept going: the next events show it adding Pods up to the maximum of 5.

Scaling back in

Stop the load, then keep checking kubectl get hpa web for the next few minutes:

ubuntu@secopslog-k8s:~/lab/scaling · Kubernetes 1.37
$ kubectl delete deployment load && kubectl wait --for=delete pod -l app=load --timeout=90s
deployment.apps "load" deleted from default namespace pod/load-84c7f9bd99-ks7fp condition met pod/load-84c7f9bd99-njdhl condition met
$ kubectl get hpa web
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE web Deployment/web cpu: 0%/50% 1 5 1 4m32s
$ kubectl describe hpa web | sed -n '/^Events:/,$p'
Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SuccessfulRescale 2m55s horizontal-pod-autoscaler New size: 3; reason: cpu resource utilization (percentage of request) above target Normal SuccessfulRescale 2m24s horizontal-pod-autoscaler New size: 4; reason: cpu resource utilization (percentage of request) above target Normal SuccessfulRescale 98s horizontal-pod-autoscaler New size: 5; reason: cpu resource utilization (percentage of request) above target Normal SuccessfulRescale 34s horizontal-pod-autoscaler New size: 4; reason: All metrics below target Normal SuccessfulRescale 19s horizontal-pod-autoscaler New size: 1; reason: All metrics below target

Read the events from the top. The HPA reached 5 Pods even after the load had stopped, because its readings were still catching up. The use then fell to 0%, but the count stayed up for about a minute before it dropped to 4 and then 1. That pause is the scale-down stabilization window. Before removing Pods, the HPA takes the highest count it computed during the window, so one quiet moment does not throw away capacity that the next burst will need. hpa.yaml sets the window to 60 seconds. The default is 300 seconds, five minutes, which is why an HPA on a real cluster seems slow to scale down. That is deliberate, and for most apps the default is right.

Hands-on

Find out what happens to a manual change while an HPA is in charge.

1. Scale by hand: kubectl scale deployment web --replicas=4

2. Look at the Deployment: kubectl get deployment web

3. Run kubectl get deployment web again every 15 seconds until READY shows 1/1

4. Read the HPA events: kubectl describe hpa web, and look at the Events at the end

5. Clean up: kubectl delete -f hpa.yaml -f web.yaml, then kubectl delete -f https://github.com/kubernetes-sigs/metrics-server/releases/download/v0.9.1/components.yaml

What you should see: step 2 shows 1/4, as three new Pods start. In step 3 the Deployment is back at 1/1 after a little over a minute. The newest event in step 4 reads New size: 1; reason: All metrics below target, counted twice now. The HPA owns the replica count, so a manual change lasts only until its next decision. It did not act at once, because the new Pods had no CPU readings yet and the HPA is cautious about Pods it cannot measure. Step 5 removes the app and metrics-server.

Remember

kubectl scale sets the replica count once. An HPA keeps setting it from metrics-server readings, measured against the Pods' CPU requests, and it scales down only after the stabilization window, five minutes by default.

Quick check
01kubectl top pods answers error: Metrics API not available. What is missing?
Incorrect — An HPA reads metrics. It does not provide them, and there was none when top started working.
Incorrect — Requests are needed for HPA percentages, not for top to answer at all.
Correct — top failed until metrics-server was installed and its APIService was Available.
Incorrect — That is a metrics-server flag, not a kubelet one, and only needed where kubelet certificates lack IP SANs.
02An HPA targets 50% CPU. Its one Pod runs at 128% of its request. How many Pods does it ask for, with a maximum of 5?
Correct — 2.56 rounds up to 3, and the first event in the lab said New size: 3.
Incorrect — The HPA always rounds up, so it never ends below what the load needs.
Incorrect — It asks for what the formula gives. It reached 5 only after further readings.
Incorrect — Four is a limit on one step, not a target. The formula gave 3.
03Load stopped three minutes ago, but your HPA still keeps 8 Pods. Its YAML has no behavior section. What is going on?
Incorrect — Possible, but the usual reason is the default window. Check kubectl describe hpa events first.
Incorrect — The HPA scaled from 5 down to 1 on its own.
Incorrect — After load stops, CPU falls towards 0%, well below target.
Correct — Without behavior, the HPA waits five minutes before removing Pods.

Related