The service moves to Kubernetes. It needs to keep answering while it is deployed, scaled, and rolled back, including when someone deploys an image that does not exist. You build that on a dedicated local kind cluster.
A kind cluster named cap-k8s with its own kubeconfig file, so your other clusters and your kubectl context are never touched.
Lessons: Containers and a Local Kubernetes Cluster: Docker or Podman, kind, and kubectl, Kubernetes Core
Two replicas with requests and limits, a non-root security context, and a Service in front of them.
Lessons: Deployments & ReplicaSets: The Rolling Update, Step by Step, Kubernetes Pod Security in Depth
Traefik (Helm chart 42.4.3) routes orders.localtest.me on port 18083 to the Service.
Lessons: Kubernetes Ingress, Helm
Readiness and liveness probes, and a drain period, so no request fails during a rollout.
metrics-server and a HorizontalPodAutoscaler between 2 and 5 replicas.
Lessons: Kubernetes Autoscaling: HPA, VPA, KEDA, and Node Autoscaling
A bad image rollout that stalls without failing traffic, kubectl rollout undo, an upgrade to 2.0.0, and a rollback.
Lessons: Progressive Delivery, Safe Database Migrations, and DORA Metrics, Blue/Green Deployments and Deployment Frequency: Instant Switch, Instant Rollback, Small Batches
| Tool | Version |
|---|---|
| docker | 24 or later |
| kind | 0.23 or later |
| kubectl | within one minor version of the cluster |
| helm | 3.14 or later |
| curl | any |
Ports: 18083 on 127.0.0.1. Resources: About 2 GB of memory and 2 CPUs free for the cluster.
What it creates (and the reset removes): the kind cluster cap-k8s; its kubeconfig and Helm folders in ~/labs/capstones/k8s; the image cap-orders:1.0.0 and 2.0.0 loaded into the cluster. Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.
One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.
mkdir -p ~/labs && cd ~/labs curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz tar -xzf capstones-lab.tar.gz && cd capstones-lab ls
All in one, with the reset afterwards even if a step fails:
bash run.sh 03-kubernetes
Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):
bash 03-kubernetes/setup.sh bash 03-kubernetes/verify.sh bash 03-kubernetes/reset.sh
This is a real run of run.sh 03-kubernetes, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.
== 1. Build two versions of the image
cap-orders:2.0.0 74MB
cap-orders:1.0.0 74MB
== 2. Create the cluster (its own kubeconfig) and load the images
Have a nice day! ๐
NAME STATUS ROLES AGE VERSION
cap-k8s-control-plane Ready control-plane 23s v1.37.0
== 3. Install the ingress controller (Traefik) and metrics-server, at pinned chart versions
metrics-server
traefik
== 4. Deploy orders: Deployment (probes, limits), Service, Ingress, HorizontalPodAutoscaler
deployment.apps/orders created
service/orders created
ingress.networking.k8s.io/orders created
horizontalpodautoscaler.autoscaling/orders created
Waiting for deployment "orders" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "orders" rollout to finish: 1 of 2 updated replicas are available...
deployment "orders" successfully rolled out
{"version": "1.0.0"}
== Deployment, Service, Ingress
PASS 2 of 2 replicas ready
PASS readiness and liveness probes are set
PASS CPU and memory requests and limits are set
PASS non-root, read-only root filesystem
PASS the Service has 2 ready endpoints
PASS the Ingress routes orders.localtest.me to version 1.0.0
== Autoscaling
PASS the HPA reads CPU from metrics-server (now 2% of requests)
PASS the HPA keeps between 2 and 5 replicas
== A broken release: an image that does not exist
PASS during the bad rollout all 10 requests were served by 1.0.0 (maxUnavailable 0)
PASS the rollout is reported failed (progress deadline exceeded)
PASS rollout undo restored 1.0.0
== A good release, then a rollback, with traffic flowing
PASS 2.0.0 rolled out
PASS no failed requests during the upgrade and the rollback (pods drain on SIGTERM)
PASS rolled back to 1.0.0
2 <none>
4 <none>
5 <none>
RESULT: all checks passed03-kubernetes/expected-output.txt03-kubernetes/k8s/app.yaml03-kubernetes/kind.yaml03-kubernetes/reset.sh03-kubernetes/setup.sh03-kubernetes/verify.shlib.sh (shared helpers)app/orders.py (the service)03-kubernetes/k8s/app.yaml# orders on Kubernetes: Deployment (probes, limits, non-root), Service, Ingress, and autoscaler.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders
labels: {app: orders}
spec:
replicas: 2
revisionHistoryLimit: 5
progressDeadlineSeconds: 60 # a rollout that makes no progress for 60 s is marked failed
selector:
matchLabels: {app: orders}
strategy:
type: RollingUpdate
rollingUpdate: {maxUnavailable: 0, maxSurge: 1} # never fewer than 2 ready pods during a rollout
template:
metadata:
labels: {app: orders}
spec:
terminationGracePeriodSeconds: 20 # longer than DRAIN_S, so draining can finish
securityContext: {runAsNonRoot: true, runAsUser: 10001, runAsGroup: 10001, seccompProfile: {type: RuntimeDefault}}
containers:
- name: orders
image: cap-orders:1.0.0
imagePullPolicy: IfNotPresent
ports: [{name: http, containerPort: 8080}]
env: [{name: DRAIN_S, value: "5"}] # keep serving 5 s after SIGTERM while endpoints update
readinessProbe: {httpGet: {path: /readyz, port: http}, periodSeconds: 3, failureThreshold: 2}
livenessProbe: {httpGet: {path: /healthz, port: http}, initialDelaySeconds: 5, periodSeconds: 10}
resources:
requests: {cpu: 50m, memory: 32Mi}
limits: {cpu: 250m, memory: 96Mi}
securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
---
apiVersion: v1
kind: Service
metadata:
name: orders
spec:
selector: {app: orders}
ports: [{name: http, port: 80, targetPort: http}]
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: orders
spec:
ingressClassName: traefik
rules:
- host: orders.localtest.me # public DNS resolves it to 127.0.0.1; curl also sends -H Host
http:
paths:
- path: /
pathType: Prefix
backend: {service: {name: orders, port: {name: http}}}
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: orders
spec:
scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: orders}
minReplicas: 2
maxReplicas: 5
metrics:
- type: Resource
resource: {name: cpu, target: {type: Utilization, averageUtilization: 60}}03-kubernetes/kind.yaml# One-node cluster; host port 18083 reaches the ingress controller's NodePort 30080.
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
extraPortMappings:
- containerPort: 30080
hostPort: 18083
listenAddress: "127.0.0.1"03-kubernetes/reset.sh#!/usr/bin/env bash # Deletes the cap-k8s cluster, the cap-orders images, and ~/labs/capstones/k8s. Your own kubeconfig # was never used. source "$(dirname "$0")/../lib.sh" WORK="$HOME/labs/capstones/k8s" kind delete cluster --name cap-k8s --kubeconfig "$WORK/kubeconfig" 2>&1 | tail -1 || true docker image rm -f cap-orders:1.0.0 cap-orders:2.0.0 > /dev/null 2>&1 || true rm -rf "$WORK" echo "capstone 3 reset: cluster cap-k8s, its images, and $WORK removed"
03-kubernetes/setup.sh#!/usr/bin/env bash
# Capstone 3, Kubernetes: Deployment -> Service -> Ingress -> probes -> resources -> autoscaling.
# A dedicated kind cluster "cap-k8s" with its own kubeconfig in ~/labs/capstones/k8s, so no other
# cluster or kubeconfig is touched. verify.sh rehearses a failed rollout and rollbacks.
source "$(dirname "$0")/../lib.sh"
need docker kind kubectl helm curl
work k8s
export KUBECONFIG="$WORK/kubeconfig" HELM_CONFIG_HOME="$WORK/helm/config" HELM_CACHE_HOME="$WORK/helm/cache" HELM_DATA_HOME="$WORK/helm/data"
port_free 18083
cp -r "$(dirname "$0")/k8s" "$(dirname "$0")/kind.yaml" "$WORK/"; cp "$APP_SRC/orders.py" "$APP_SRC/Dockerfile" "$WORK/"
cd "$WORK"
say "1. Build two versions of the image"
docker build -q -t cap-orders:1.0.0 --build-arg VERSION=1.0.0 . > /dev/null
docker build -q -t cap-orders:2.0.0 --build-arg VERSION=2.0.0 . > /dev/null
docker image ls cap-orders --format ' {{.Repository}}:{{.Tag}} {{.Size}}'
say "2. Create the cluster (its own kubeconfig) and load the images"
kind create cluster --name cap-k8s --config kind.yaml --kubeconfig "$KUBECONFIG" --wait 180s 2>&1 | tail -1
kind load docker-image cap-orders:1.0.0 cap-orders:2.0.0 --name cap-k8s > /dev/null 2>&1
kubectl get nodes
say "3. Install the ingress controller (Traefik) and metrics-server, at pinned chart versions"
helm repo add traefik https://traefik.github.io/charts > /dev/null
helm repo add metrics-server https://kubernetes-sigs.github.io/metrics-server/ > /dev/null
helm repo update > /dev/null
helm install traefik traefik/traefik --version 42.4.3 -n traefik --create-namespace --wait --timeout 4m \
--set service.spec.type=NodePort --set ports.web.nodePort=30080 --set ingressClass.isDefaultClass=true > /dev/null
helm install metrics-server metrics-server/metrics-server --version 3.14.0 -n kube-system --wait --timeout 4m \
--set 'args={--kubelet-insecure-tls}' > /dev/null
helm list -A --short
say "4. Deploy orders: Deployment (probes, limits), Service, Ingress, HorizontalPodAutoscaler"
kubectl apply -f k8s/app.yaml
kubectl rollout status deployment/orders --timeout=120s
for _ in $(seq 30); do curl -fsS -m 3 -H 'Host: orders.localtest.me' http://127.0.0.1:18083/version 2>/dev/null && break; sleep 2; done; echo03-kubernetes/verify.sh#!/usr/bin/env bash
# Checks capstone 3, then rehearses a failed rollout and two rollbacks.
source "$(dirname "$0")/../lib.sh"
need kubectl curl jq
work k8s
export KUBECONFIG="$WORK/kubeconfig"
U=http://127.0.0.1:18083; H='Host: orders.localtest.me'
ver() { curl -fsS -m 3 -H "$H" "$U/version" 2>/dev/null | jq -r .version 2>/dev/null || echo failed; }
# send a request every 0.2 s in the background during a rollout. The loop stops when asked, when the
# work folder goes away, or after 3,000 requests (10 minutes), whichever comes first. watch_stop
# waits for that loop by its PID in this shell, and leaves the failure count in $WORK/fails.
watch_start() {
rm -f "$WORK/stop" "$WORK/fails"
( f=0; n=0; while [ ! -f "$WORK/stop" ] && [ -d "$WORK" ] && [ "$n" -lt 3000 ]; do
curl -fsS -m 2 -o /dev/null -H "$H" "$U/version" 2>/dev/null || f=$((f + 1)); n=$((n + 1)); sleep 0.2
done; [ -d "$WORK" ] && echo "$f" > "$WORK/fails" ) &
WATCH_PID=$!
}
watch_stop() { touch "$WORK/stop"; wait "$WATCH_PID" 2>/dev/null || true; rm -f "$WORK/stop"; }
dep() { kubectl get deploy orders -o json; }
say "Deployment, Service, Ingress"
ready=$(kubectl get deploy orders -o jsonpath='{.status.readyReplicas}')
[ "$ready" = 2 ] && ok "2 of 2 replicas ready" || bad "$ready replicas ready, want 2"
dep | jq -e '.spec.template.spec.containers[0] | .readinessProbe and .livenessProbe' > /dev/null && ok "readiness and liveness probes are set" || bad "probes missing"
dep | jq -e '.spec.template.spec.containers[0].resources | .requests.cpu and .limits.memory' > /dev/null && ok "CPU and memory requests and limits are set" || bad "resources missing"
dep | jq -e '.spec.template.spec.securityContext.runAsNonRoot and .spec.template.spec.containers[0].securityContext.readOnlyRootFilesystem' > /dev/null && ok "non-root, read-only root filesystem" || bad "pod security settings missing"
eps=$(kubectl get endpointslices -l kubernetes.io/service-name=orders -o json | jq '[.items[].endpoints[] | select(.conditions.ready)] | length')
[ "$eps" = 2 ] && ok "the Service has 2 ready endpoints" || bad "the Service has $eps ready endpoints"
v=$(ver); [ "$v" = 1.0.0 ] && ok "the Ingress routes orders.localtest.me to version 1.0.0" || bad "the Ingress returned version '$v'"
say "Autoscaling"
t=""; for _ in $(seq 40); do t=$(kubectl get hpa orders -o jsonpath='{.status.currentMetrics[0].resource.current.averageUtilization}' 2>/dev/null); [ -n "$t" ] && break; sleep 3; done
[ -n "$t" ] && ok "the HPA reads CPU from metrics-server (now ${t}% of requests)" || bad "the HPA has no CPU metric yet (metrics-server not ready)"
kubectl get hpa orders -o json | jq -e '.spec.minReplicas == 2 and .spec.maxReplicas == 5' > /dev/null && ok "the HPA keeps between 2 and 5 replicas" || bad "HPA bounds wrong"
say "A broken release: an image that does not exist"
kubectl set image deployment/orders orders=cap-orders:9.9.9 > /dev/null
served=0; for _ in $(seq 10); do [ "$(ver)" = 1.0.0 ] && served=$((served + 1)); sleep 1; done
[ "$served" = 10 ] && ok "during the bad rollout all 10 requests were served by 1.0.0 (maxUnavailable 0)" || bad "only $served of 10 requests succeeded during the bad rollout"
if kubectl rollout status deployment/orders --timeout=75s > /dev/null 2>&1; then bad "the bad rollout did not fail"; else ok "the rollout is reported failed (progress deadline exceeded)"; fi
kubectl rollout undo deployment/orders > /dev/null 2>&1 && kubectl rollout status deployment/orders --timeout=90s > /dev/null
sleep 6
v=$(ver); [ "$v" = 1.0.0 ] && ok "rollout undo restored 1.0.0" || bad "after undo the version is '$v'"
say "A good release, then a rollback, with traffic flowing"
watch_start
kubectl set image deployment/orders orders=cap-orders:2.0.0 > /dev/null && kubectl rollout status deployment/orders --timeout=90s > /dev/null
sleep 6
v=$(ver); [ "$v" = 2.0.0 ] && ok "2.0.0 rolled out" || bad "after the upgrade the version is '$v'"
kubectl rollout undo deployment/orders > /dev/null 2>&1 && kubectl rollout status deployment/orders --timeout=90s > /dev/null
sleep 6
watch_stop; fails=$(cat "$WORK/fails" 2>/dev/null || echo unknown)
[ "$fails" = 0 ] && ok "no failed requests during the upgrade and the rollback (pods drain on SIGTERM)" || bad "$fails failed requests during the upgrade and the rollback"
v=$(ver); [ "$v" = 1.0.0 ] && ok "rolled back to 1.0.0" || bad "after the rollback the version is '$v'"
kubectl rollout history deployment/orders | tail -4
summary| Symptom | Cause | Fix |
|---|---|---|
| kind create fails with "too many open files" | The inotify limit is too low for a second cluster. | sudo sysctl -w fs.inotify.max_user_instances=512 (until the next reboot). |
| curl to orders.localtest.me fails | Traefik is not ready yet, or your DNS does not resolve localtest.me. | Wait for the traefik pod; or use curl -H "Host: orders.localtest.me" http://127.0.0.1:18083/. |
| Your own kubectl commands now point somewhere else | They should not: the capstone uses KUBECONFIG in its folder only. | kubectl config current-context shows your context as before; if not, kubectl config use-context <yours>. |
Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.
bash 03-kubernetes/reset.sh
It removes: the kind cluster cap-k8s; its kubeconfig and Helm folders in ~/labs/capstones/k8s; the image cap-orders:1.0.0 and 2.0.0 loaded into the cluster. Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.
| Provider | Equivalent |
|---|---|
| AWS | EKS with the AWS Load Balancer Controller for Ingress, metrics-server, and the same manifests; nodes cost money while they exist. |
| Azure | AKS with the application routing add-on for Ingress, and the same manifests. |
| Google Cloud | GKE Autopilot with GKE Ingress or Gateway, and the same manifests. |
verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.
| Criterion | Meets | Exceeds |
|---|---|---|
| Availability | No request fails during a normal rollout. | No request fails during a bad rollout either, and you can explain why. |
| Resources | Every container has requests and limits. | Requests are based on measured use, as in the rightsizing capstone lesson. |
| Security | Pods run as non-root with a read-only filesystem. | A namespace Pod Security level enforces it. |
| Recovery | You can undo a rollout. | You can roll back to a named revision and show its image. |
Then test what you know with the assessments.