Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: rollouts, rollbacks, autoscaling and environment overlays

Turn the lesson 2 service into a Kustomize base with dev and prod overlays, roll out a new version, roll back a broken one, and watch a HorizontalPodAutoscaler add replicas under load.

Contentsand lesson path

What you will learn

  • Perform and roll back a rolling update, scale with a HorizontalPodAutoscaler, and express per-environment differences with Kustomize overlays or a Helm chart.

Prerequisites: Containerization

01. Goal and setup

You will describe one service for two environments without copying YAML, ship a change to prod, recover from a bad release, and scale on CPU. You need the kind cluster and app.py from lesson 2. kubectl includes Kustomize, so kubectl kustomize and kubectl apply -k need nothing extra.

The setup commands create the folders and namespace files, and install metrics-server v0.9.1, which feeds CPU and memory usage to kubectl top and to the autoscaler. kind kubelets use self-signed serving certificates, so the patch adds --kubelet-insecure-tls; use that flag only on a local test cluster.

The kubectl kustomize outputs below come from real runs with kubectl v1.37.2 (which bundles kustomize v5.8.1) and with the standalone kustomize build v5.8.3; both print the same hash suffixes, because the suffix is computed only from the ConfigMap's kind, name and data. If you change a value, your suffix changes too, and one byte is enough: web-code-4t626bk292 assumes that app.py ends with a newline, as most editors save it, and without that final newline the suffix is web-code-t8d78c9gtt. What to check is which names change and which do not. Outputs from the cluster are illustrative, use the same suffixes, and cut long lines with an ellipsis.

Layout
k8s-lab/k8s/
├── base/
│   ├── kustomization.yaml   what every environment shares
│   ├── deployment.yaml
│   ├── service.yaml
│   └── app.py               copied from lesson 2
└── overlays/
    ├── dev/                 kustomization.yaml, namespace.yaml
    └── prod/                kustomization.yaml, namespace.yaml, hpa.yaml
Terminal
cd k8s-lab
mkdir -p k8s/base k8s/overlays/dev k8s/overlays/prod
cp app.py k8s/base/
for env in dev prod; do
  printf 'apiVersion: v1\nkind: Namespace\nmetadata:\n  name: web-%s\n' "$env" \
    > "k8s/overlays/$env/namespace.yaml"
done
MS=https://github.com/kubernetes-sigs/metrics-server/releases/download
kubectl apply -f "$MS/v0.9.1/components.yaml"
ARG='{"op":"add","path":"/spec/template/spec/containers/0/args/-",'
ARG+='"value":"--kubelet-insecure-tls"}'
kubectl -n kube-system patch deployment metrics-server --type=json -p "[$ARG]"
kubectl -n kube-system rollout status deployment/metrics-server

02. Step 1: A base and two overlays

The base holds what every environment shares. Compared with lesson 2, the Deployment has no replicas field: in prod an autoscaler owns that number, and a value in the manifest would reset it on every apply. It also sets the rollout strategy and a short preStop sleep, both explained in step 2. configMapGenerator builds both ConfigMaps and adds a hash of their content to each name.

YAML · k8s/base/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
  - service.yaml
configMapGenerator:
  - name: web-code
    files:
      - app.py
  - name: web-config
    literals:
      - GREETING=hello
      - APP_VERSION=v1
YAML · k8s/base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  selector:
    matchLabels:
      app: web
  strategy:
    rollingUpdate: {maxSurge: 25%, maxUnavailable: 0}
  template:
    metadata:
      labels:
        app: web
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: app
          image: docker.io/library/python:3.13-alpine
          command: ["python", "/app/app.py"]
          ports:
            - containerPort: 8080
          envFrom:
            - configMapRef:
                name: web-config
          volumeMounts:
            - name: code
              mountPath: /app
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 64Mi}
          readinessProbe:
            httpGet: {path: /ready, port: 8080}
            periodSeconds: 5
          livenessProbe:
            httpGet: {path: /healthz, port: 8080}
            periodSeconds: 10
          lifecycle:
            preStop:
              exec: {command: ["sleep", "5"]}
      volumes:
        - name: code
          configMap:
            name: web-code
YAML · k8s/base/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 8080

Each overlay points at the base and states only what differs: a namespace, a greeting, one fixed replica in dev, and in prod an HPA plus an images entry that pins the tag. behavior: merge adds keys to the base ConfigMap instead of replacing it.

YAML · k8s/overlays/dev/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: web-dev
resources:
  - ../../base
  - namespace.yaml
replicas:
  - name: web
    count: 1
configMapGenerator:
  - name: web-config
    behavior: merge
    literals:
      - GREETING=hello from dev
YAML · k8s/overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: web-prod
resources:
  - ../../base
  - namespace.yaml
  - hpa.yaml
configMapGenerator:
  - name: web-config
    behavior: merge
    literals:
      - GREETING=hello from prod
images:
  - name: docker.io/library/python
    newTag: 3.13-alpine
YAML · k8s/overlays/prod/hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 2
  maxReplicas: 6
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

Render both overlays before applying anything. Rendering is local and safe, and it is the best way to review a change.

Terminal
kubectl kustomize k8s/overlays/prod | grep -E "name: web-c|image:"
kubectl kustomize k8s/overlays/dev | grep -E "name: web-c|replicas:"
Expected output (kubectl v1.37.2)
  name: web-code-4t626bk292
  name: web-config-7cgb2tk4g2
            name: web-config-7cgb2tk4g2
        image: docker.io/library/python:3.13-alpine
          name: web-code-4t626bk292
  name: web-code-4t626bk292
  name: web-config-kh9g88664f
  replicas: 1
            name: web-config-kh9g88664f
          name: web-code-4t626bk292

The code ConfigMap is the same in both environments, so it has the same name. The settings differ, so each environment gets its own web-config-<hash>, and Kustomize rewrote the references in the Deployment to match. Now apply both.

Terminal
kubectl apply -k k8s/overlays/dev
kubectl apply -k k8s/overlays/prod
kubectl -n web-prod rollout status deployment/web
kubectl get deployments -n web-dev; kubectl get deployments -n web-prod
Illustrative output
namespace/web-dev created
configmap/web-code-4t626bk292 created
configmap/web-config-kh9g88664f created
service/web created
deployment.apps/web created
namespace/web-prod created
configmap/web-code-4t626bk292 created
configmap/web-config-7cgb2tk4g2 created
service/web created
deployment.apps/web created
horizontalpodautoscaler.autoscaling/web created
deployment "web" successfully rolled out
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    1/1     1            1           35s
NAME   READY   UP-TO-DATE   AVAILABLE   AGE
web    2/2     2            2           33s

03. Step 2: Roll out a new version

A Deployment starts a rollout only when its Pod template (spec.template) changes; scaling does not create a revision. Edit the prod overlay as below: add APP_VERSION=v2 and move to the 3.14-alpine tag. Then render again.

YAML · k8s/overlays/prod/kustomization.yaml (edited)
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: web-prod
resources:
  - ../../base
  - namespace.yaml
  - hpa.yaml
configMapGenerator:
  - name: web-config
    behavior: merge
    literals:
      - GREETING=hello from prod
      - APP_VERSION=v2
images:
  - name: docker.io/library/python
    newTag: 3.14-alpine
Terminal
kubectl kustomize k8s/overlays/prod | grep -E "name: web-c|image:"
kubectl apply -k k8s/overlays/prod
kubectl -n web-prod rollout status deployment/web
kubectl -n web-prod rollout history deployment/web
Expected output of the first command (kubectl v1.37.2)
  name: web-code-4t626bk292
  name: web-config-ch4bf9c7tm
            name: web-config-ch4bf9c7tm
        image: docker.io/library/python:3.14-alpine
          name: web-code-4t626bk292
Illustrative output of the other commands
namespace/web-prod unchanged
configmap/web-code-4t626bk292 unchanged
configmap/web-config-ch4bf9c7tm created
service/web unchanged
deployment.apps/web configured
horizontalpodautoscaler.autoscaling/web unchanged
Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been upd…
Waiting for deployment "web" rollout to finish: 1 old replicas are pending terminatio…
deployment "web" successfully rolled out
deployment.apps/web
REVISION  CHANGE-CAUSE
1         <none>
2         <none>

The new settings produced a new ConfigMap name, which changed the Pod template, so the configuration change rolls out like any other release. A plain ConfigMap edited in place would not: running Pods keep the environment they started with. With Helm, the usual equivalent is a checksum/config annotation on the Pod template computed from the ConfigMap template. Kustomize does not delete the old web-config-7cgb2tk4g2, and that is useful: the previous ReplicaSet still points at it, so a rollback gets the old settings back too.

The strategy controls the pace. maxSurge: 25% of 2 replicas rounds up to 1 extra Pod; maxUnavailable: 0 means an old Pod is removed only after a new one is Ready. So capacity never drops below 2 because of the rollout itself. That is not the same as zero errors. Requests can still fail if readiness does not reflect real readiness, if the app drops in-flight requests on SIGTERM, or if a Pod is stopped before load balancers notice. The preStop sleep gives kube-proxy and the Gateway a few seconds to stop sending new requests before the app gets SIGTERM, and terminationGracePeriodSeconds must be long enough for that sleep plus draining. Changes must also be backward compatible, because old and new versions serve side by side.

04. Step 3: Recover from a bad release

Ship a typo on purpose. kubectl set image takes the container name and a full image reference; app=3.41-alpine would mean an image called 3.41-alpine on Docker Hub. The tag 3.41-alpine does not exist, so the new Pod can never pull its image.

Terminal
kubectl -n web-prod set image deployment/web \
  app=docker.io/library/python:3.41-alpine
kubectl -n web-prod rollout status deployment/web --timeout=60s
kubectl -n web-prod get pods -l app=web
Illustrative output
deployment.apps/web image updated
Waiting for deployment "web" rollout to finish: 1 out of 2 new replicas have been upd…
error: timed out waiting for the condition
NAME                   READY   STATUS             RESTARTS   AGE
web-6d9c7b5f4d-7qkzm   1/1     Running            0          4m12s
web-6d9c7b5f4d-xw2rt   1/1     Running            0          4m3s
web-78f6c9d8b7-p9d2j   0/1     ImagePullBackOff   0          62s

Because maxUnavailable is 0, both old Pods are still serving. The default of 25% would behave the same with 2 replicas, because maxUnavailable rounds down (25% of 2 is 0.5, so 0); with 4 or more replicas, though, the default would already have removed an old Pod before the new one failed. Kubernetes does not roll back by itself: after progressDeadlineSeconds (600 seconds by default) the Deployment reports Progressing=False with reason ProgressDeadlineExceeded, and your pipeline has to act on it. rollout undo copies the previous template back and runs another rolling update with the same rules; it is fast here because the old Pods never left.

Terminal
kubectl -n web-prod rollout undo deployment/web
kubectl -n web-prod rollout status deployment/web
kubectl -n web-prod rollout history deployment/web
Illustrative output
deployment.apps/web rolled back
deployment "web" successfully rolled out
deployment.apps/web
REVISION  CHANGE-CAUSE
1         <none>
3         <none>
4         <none>

Revision 2 came back as revision 4: an undo is recorded as a new revision. set image and rollout undo are imperative, so the cluster and your files can drift apart. Here the files already hold the good tag, but in a real incident, fix or revert the change in Git as well, or the next kubectl apply -k (or GitOps sync) brings the bad version back.

05. Step 4: Scale on CPU with an HPA

Every 15 seconds the HPA controller reads usage from the metrics API and divides each Pod CPU usage by its CPU request. It then computes the desired replicas as current replicas × current utilisation ÷ target, rounded up, within minReplicas and maxReplicas. Each /work request burns about 20 ms of CPU, so one busy client is plenty.

Terminal · stop the watch with Ctrl+C
kubectl top pods -n web-prod
kubectl -n web-prod run load --image=busybox:1.37 --restart=Never -- \
  /bin/sh -c 'while true; do wget -q -O /dev/null http://web/work; done'
kubectl -n web-prod get hpa web --watch
Illustrative output (your percentages will differ)
NAME                   CPU(cores)   MEMORY(bytes)
web-6d9c7b5f4d-7qkzm   1m           11Mi
web-6d9c7b5f4d-xw2rt   1m           11Mi
pod/load created
NAME   REFERENCE        TARGETS        MINPODS   MAXPODS   REPLICAS   AGE
web    Deployment/web   cpu: 2%/70%    2         6         2          14m
web    Deployment/web   cpu: 840%/70%  2         6         2          15m
web    Deployment/web   cpu: 840%/70%  2         6         6          15m
web    Deployment/web   cpu: 290%/70%  2         6         6          16m

Then stop the load and watch again. Scale-down waits for a 300-second stabilisation window by default, so replicas return to 2 after about five minutes. That delay is deliberate: it stops the HPA from removing Pods during a short lull and adding them back a minute later.

Terminal
kubectl -n web-prod delete pod load
kubectl -n web-prod get hpa web --watch

06. Check your understanding

Practice check · 3 questions

Rollout rules and generated config

Three questions about the choices in this lab.

Q1. A Deployment has 4 replicas, `maxSurge: 25%` and `maxUnavailable: 0`. Not counting Pods that are already terminating, what is the largest number of its Pods that can exist during a rolling update?
Q2. A new image never becomes Ready and `progressDeadlineSeconds` has passed. What has Kubernetes done on its own?
Q3. You change a literal in a `configMapGenerator` and run `kubectl apply -k`. Why do the Pods roll?
Practice only: not graded, not saved, not evidence.

07. Apply it

Carry this into the skill project:

  • Add the Gateway and HTTPRoute from lesson 2 to the base, and give each overlay its own host name with a patch.
  • In your pipeline, run kubectl rollout status --timeout=… after every apply and fail the job if it times out, so a stuck rollout is noticed in minutes rather than at the 600-second deadline.
  • Add a PodDisruptionBudget with minAvailable: 1 to prod, then drain the node (kubectl drain --ignore-daemonsets) on a multi-node kind cluster and watch the eviction wait for it.

08. Review prompt

Without looking back, explain: what change creates a new Deployment revision; what maxSurge and maxUnavailable: 0 guarantee and what they do not; what happens, and what does not happen, when a rollout misses its progress deadline; why kubectl set image needs a full image reference and why an imperative fix must also go into Git; how a configMapGenerator change reaches running Pods; how the HPA computes CPU utilisation and two reasons it can show <unknown>; and why a manifest should not set replicas when an HPA owns them.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check