Scaling by hand and automatically
More copies when busy, fewer when quiet.
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: 7a00ae4505868949fcea4ba4287467e64dd7ce22235950a2ac1784d2ca844dfbA 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.
apiVersion: apps/v1kind: Deploymentmetadata:name: webspec:replicas: 1selector:matchLabels:app: webtemplate:metadata:labels:app: webspec:containers:- name: nginximage: nginx:1.30.6-alpineresources:requests:cpu: 50mlimits:cpu: 200m---apiVersion: v1kind: Servicemetadata:name: webspec:selector:app: webports:- port: 80
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:
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:
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:
--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:
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:
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata:name: webspec:scaleTargetRef:apiVersion: apps/v1kind: Deploymentname: webminReplicas: 1maxReplicas: 5metrics:- type: Resourceresource:name: cputarget:type: UtilizationaverageUtilization: 50behavior:scaleDown:stabilizationWindowSeconds: 60 # lab only; the default is 300
Apply it, and run kubectl get hpa web until the TARGETS column shows a percentage:
cpu: 0%/50% is current use against the target. Now add load: two busybox Pods fetch the page over and over in a loop.
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:
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:
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.
kubectl top pods answers error: Metrics API not available. What is missing?top started working.top to answer at all.top failed until metrics-server was installed and its APIService was Available.New size: 3.behavior section. What is going on?kubectl describe hpa events first.behavior, the HPA waits five minutes before removing Pods.