# Capstone: a production-ready release of shop-web

Everything from the course in one Helm chart: config, probes, limits, security, a disruption budget, a network policy and autoscaling, with dev and prod values and a zero-downtime release.

Course: [Kubernetes & Helm](https://devops.rajeev.pro/courses/kubernetes), lesson 16. About 60 minutes, intermediate. Source: https://devops.rajeev.pro/courses/kubernetes/16-capstone-production-release

## What you will learn

- Build one Helm chart that carries every production setting from this course
- Run dev and prod from the same chart with different values files
- Prove a release has zero failed requests, and roll back a bad one
- Pass the restricted Pod Security standard and lock traffic down with a NetworkPolicy
- Run it free on kind, and know what changes on EKS

> **Lab status.** **Verified:** `helm lint` and `helm template` of the chart for dev and prod, with Helm 4.3.1. The output shown is real. <br />**Code walkthrough:** the install, release and rollback on kind. The steps are the same ones lessons 4 to 14 ran for real on EKS, but this exact chart hasn't been run end to end on a cluster yet. Expect to fix small things, as you would at work. <br />**Cloud lab:** Track B on EKS is optional and costs money while it runs.

Fifteen lessons, fifteen separate pieces. In a real job they arrive together: someone asks you to "put shop-web
on Kubernetes properly" and expects probes, limits, config, security, safe releases and autoscaling in one
deliverable. This capstone is that deliverable: one Helm chart, two environments, and evidence that a release
doesn't drop a single request.

## What you're building

- **One chart** (`shop`) starting from `helm create` (lesson 13), with every production setting from the course.
- **Two values files**: `values-dev.yaml` (1 replica, cheap) and `values-prod.yaml` (autoscaling 3 to 6).
- **Evidence**: a client calling the app 5 times a second through a release, a failed release rolled back, and a
  privileged Pod refused.

The app is shop-web from lesson 2: `/api` returns its version, `/healthz` is the probe endpoint, and the
`v3-broken` image crashes on start.

> **Figure.** The chart helm/shop, with values.yaml, values-dev.yaml, values-prod.yaml and templates for the deployment, service, hpa, pdb, configmap, networkpolicy and ingress, is released with helm upgrade shop ./shop -n shop -f values-prod.yaml --wait into namespace shop, which enforces the restricted Pod Security standard. Inside, a NetworkPolicy lets in only the probe Pod labelled role=frontend, which calls /api five times a second, and the ingress-nginx namespace. Traffic goes to Service shop on port 80, then to three shop-web Pods, non-root with a read-only filesystem, spread over worker 1 and worker 2. An HPA keeps 3 to 6 replicas on CPU, a PDB allows maxUnavailable 1, and a ConfigMap feeds envFrom with a checksum. A Pod without role=frontend times out, and a privileged Pod is refused at admission.

## The chart

```text
shop/
├── Chart.yaml            # name shop, version 1.0.0, appVersion v1
├── values.yaml           # defaults: every setting below
├── values-dev.yaml
├── values-prod.yaml
└── templates/
    ├── configmap.yaml    # new: non-secret settings
    ├── deployment.yaml   # + envFrom, strategy, config checksum, topology spread
    ├── hpa.yaml
    ├── ingress.yaml
    ├── networkpolicy.yaml  # new
    ├── pdb.yaml          # new
    ├── service.yaml
    ├── serviceaccount.yaml
    └── tests/test-connection.yaml
```

Each default in `values.yaml` maps to a lesson:

```yaml
# values.yaml (the production settings)
config: # lesson 6: settings in a ConfigMap, not baked into the image
  GREETING: 'Hello from the capstone'
  APP_COLOR: '#4f7a65'

resources: # lesson 7: requests for scheduling, a memory limit against leaks
  requests:
    cpu: 100m
    memory: 64Mi
  limits:
    memory: 128Mi

strategy: # lesson 14: never drop below full capacity during a release
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1
    maxUnavailable: 0

readinessProbe: # lesson 4: no traffic until /healthz answers
  httpGet:
    path: /healthz
    port: http
  periodSeconds: 2

podDisruptionBudget: # lesson 11: drains take one Pod at a time
  enabled: true
  maxUnavailable: 1

networkPolicy: # lesson 8: only role=frontend Pods and the ingress controller get in
  enabled: true
  ingressNamespace: ingress-nginx

topologySpread: true # lesson 11: spread replicas across nodes
```

Three template changes are worth reading closely. The Deployment loads the ConfigMap as environment variables
and carries a checksum of it, so changing a setting rolls the Pods:

```yaml
# templates/deployment.yaml (excerpt)
template:
  metadata:
    annotations:
      # Restart Pods when the ConfigMap changes.
      checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
  spec:
    containers:
      - name: shop
        envFrom:
          - configMapRef:
              name: {{ include "shop.fullname" . }}
```

Without that annotation, a new greeting would update the ConfigMap and change nothing: Pods read environment
variables once, at start.

The NetworkPolicy allows two sources and nothing else:

```yaml
# templates/networkpolicy.yaml (excerpt)
ingress:
  - from:
      - podSelector:
          matchLabels:
            role: frontend
      - namespaceSelector:
          matchLabels:
            kubernetes.io/metadata.name: {{ .Values.networkPolicy.ingressNamespace }}
    ports:
      - port: http
```

Lesson 8's lab removed its policies because a default-deny broke the load balancer. Allowing the ingress
controller's namespace here is the fix. And `helm test` runs a Pod too, so `tests/test-connection.yaml` carries
`role: frontend`, or the chart's own test would time out against its own policy.

## The security baseline

The chart passes the **restricted** Pod Security standard from lesson 8:

```yaml
# values.yaml (security)
serviceAccount:
  automount: false # the app never calls the Kubernetes API
podSecurityContext:
  runAsNonRoot: true
  runAsUser: 10001
  seccompProfile:
    type: RuntimeDefault
securityContext:
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ['ALL']
```

`readOnlyRootFilesystem` works because shop-web writes nothing to disk. An app that needs a scratch directory
gets an `emptyDir` volume mounted there instead of a writable image. Not mounting the service account token
means a compromised container has no credentials for the cluster API.

## Dev and prod from one chart

Each environment file holds only what differs:

```yaml
# values-dev.yaml
replicaCount: 1
config:
  GREETING: 'Hello from dev'
podDisruptionBudget:
  enabled: false # one replica + a budget = every drain blocked
```

```yaml
# values-prod.yaml
config:
  GREETING: 'Hello from production'
autoscaling:
  enabled: true
  minReplicas: 3
  maxReplicas: 6
```

Check what each renders before installing anything:

```text
$ helm lint ./shop -f shop/values-prod.yaml
==> Linting ./shop
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, 0 chart(s) failed
$ helm template shop ./shop -f shop/values-dev.yaml | grep '^kind:' | sort | uniq -c
      1 kind: ConfigMap
      1 kind: Deployment
      1 kind: NetworkPolicy
      1 kind: Pod
      1 kind: Service
      1 kind: ServiceAccount
$ helm template shop ./shop -f shop/values-prod.yaml | grep '^kind:' | sort | uniq -c
      1 kind: ConfigMap
      1 kind: Deployment
      1 kind: HorizontalPodAutoscaler
      1 kind: NetworkPolicy
      1 kind: Pod
      1 kind: PodDisruptionBudget
      1 kind: Service
      1 kind: ServiceAccount
$ helm template shop ./shop -f shop/values-dev.yaml | grep -E 'replicas:|GREETING'
  GREETING: Hello from dev
  replicas: 1
$ helm template shop ./shop -f shop/values-prod.yaml | grep -E 'replicas:|minReplicas|maxReplicas|GREETING'
  GREETING: Hello from production
  minReplicas: 3
  maxReplicas: 6
```

(The `Pod` is the `helm test` hook.) Prod has two extra objects, the HPA and the PDB, and **no `replicas:`
line**: when autoscaling is on, the chart leaves the count to the HPA. A fixed value would reset the HPA's choice
on every `helm upgrade`. The rendered Deployment also shows the release strategy and security settings landed
where they should:

```text
$ helm template shop ./shop -f shop/values-prod.yaml --show-only templates/deployment.yaml | grep -A3 -E 'strategy:|checksum|securityContext:'
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
--
        checksum/config: c491dc2f7930514e108f0bebc5bb1b32d6a54381aadd5477db6658aeaf1f4b27
...
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        seccompProfile:
```

## Track A: kind (free)

> **Figure.** Top: the chart shop renders with -f values-dev.yaml into 6 objects, replicas 1 and Hello from dev, with no PDB because one replica plus a budget blocks every drain; with -f values-prod.yaml it renders 8 objects, adding an HPA with 3 to 6 replicas and a PDB, and no replicas line so the HPA owns the count. Both are checked locally with helm lint and helm template, which CI should run for both files on every pull request. Bottom: Track A, kind, free: a control-plane node and two workers, images loaded with kind load docker-image, metrics-server from Helm with --kubelet-insecure-tls, traffic through a Service and ingress-nginx. Track B, EKS, optional: images from ECR, an ALB Ingress with className alb and target-type ip, metrics-server as an EKS add-on, about 0.10 dollars an hour for the control plane plus nodes and the ALB, then destroy.

A three-node kind cluster (one control plane, two workers, so the disruption budget and topology spread have
somewhere to move Pods):

```yaml
# kind.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
name: capstone
nodes:
  - role: control-plane
  - role: worker
  - role: worker
```

```sh
$ kind create cluster --config kind.yaml
$ docker build -t shop-web:v1 --build-arg APP_VERSION=v1 ./app
$ docker build -t shop-web:v2 --build-arg APP_VERSION=v2 ./app
$ docker build -t shop-web:v3-broken -f ./app/Dockerfile.broken ./app
$ docker pull busybox:1.37
$ kind load docker-image shop-web:v1 shop-web:v2 shop-web:v3-broken busybox:1.37 --name capstone
```

Pull busybox first: `kind load` copies images from your local Docker and fails the whole command if one is
missing. The chart's `pullPolicy: IfNotPresent` then uses the loaded images instead of trying a registry.

The autoscaler needs metrics-server, which on kind needs `--kubelet-insecure-tls` because kind's kubelets use
self-signed certificates:

```sh
$ helm repo add metrics-server https://kubernetes-sigs.github.io/metrics-server/
$ helm install metrics-server metrics-server/metrics-server -n kube-system --set "args={--kubelet-insecure-tls}" --wait
$ kubectl create namespace shop
$ kubectl label namespace shop pod-security.kubernetes.io/enforce=restricted
$ helm install shop ./shop -n shop -f shop/values-prod.yaml --wait --timeout 4m
$ kubectl get deploy,svc,hpa,pdb,networkpolicy -n shop
$ helm test shop -n shop
```

You should see 3 ready Pods spread over both workers, the HPA reading CPU, and `helm test` passing.

### Prove a zero-downtime release

`probe.yaml` is a Pod labelled `role=frontend` that calls `/api` five times a second for 75 seconds and prints
the version it got, or `FAIL`:

```yaml
# probe.yaml (the loop)
command:
  - sh
  - -c
  - |
    for i in $(seq 1 375); do
      if r=$(wget -qO- -T 2 http://shop/api); then
        echo "$r" | grep -o '"version": "v[0-9]"'
      else
        echo FAIL
      fi
      sleep 0.2
    done
```

Start it, release v2 while it runs, and count:

```sh
$ kubectl apply -n shop -f probe.yaml && kubectl wait -n shop --for=condition=Ready pod/probe
$ helm upgrade shop ./shop -n shop -f shop/values-prod.yaml --set image.tag=v2 --wait
$ kubectl wait -n shop --for=jsonpath='{.status.phase}'=Succeeded pod/probe --timeout=120s
$ kubectl logs -n shop probe | sort | uniq -c
```

The goal: v1 lines, then v2 lines, and **zero** `FAIL`. If you see failures, the usual causes are a readiness
probe that passes before the app can serve, or Pods killed before the Service stops sending them traffic (add a
short `preStop` sleep). Finding and fixing that is the most realistic part of this project.

Then the bad release and the rollback, as in lesson 13:

```sh
$ helm upgrade shop ./shop -n shop -f shop/values-prod.yaml --set image.tag=v3-broken --wait --timeout 60s
$ helm rollback shop 2 -n shop --wait
$ helm history shop -n shop
```

The upgrade should fail with the v2 Pods still serving (`maxUnavailable: 0` guarantees it), and the rollback
becomes revision 4.

Finish with the other checks: drain a worker (`kubectl drain <node> --ignore-daemonsets`) and watch the PDB let
Pods move one at a time; call the app from a Pod without `role=frontend` and see it time out; and try a
privileged Pod in the namespace and see it refused. `run.sh` in the capstone folder runs all of it in order. When
you're done:

```sh
$ kind delete cluster --name capstone
```

## Track B: EKS (optional)

The same chart runs on the EKS cluster from lesson 3 with three changes:

1. **Images** come from ECR: `--set image.repository=<account>.dkr.ecr.<region>.amazonaws.com/shop-web`.
2. **Traffic** comes through the AWS Load Balancer Controller (lesson 5): enable the chart's Ingress with
   `className: alb` and the `alb.ingress.kubernetes.io/scheme` and `target-type: ip` annotations, and set
   `networkPolicy.ingressNamespace` so the policy allows it. With `target-type: ip` the ALB connects straight to
   Pod IPs from the VPC, so check your policy allows that path too.
3. **metrics-server** is the EKS add-on, so skip the Helm install.

EKS costs about $0.10 an hour for the control plane plus the nodes and the load balancer (lesson 3 has the
prices). Run it for the evidence you need, then `terraform destroy`, and check the console for leftover load
balancers and volumes.

## Ship it

Put the chart, `kind.yaml`, `probe.yaml` and `run.sh` in a public repository with a README that shows the probe
counts and the rollback history. Add a CI job that runs `helm lint` and `helm template` for both values files on
every pull request: it's cheap, catches most chart mistakes, and is exactly what lesson 13 recommended.

## Mission: Release shop-web with zero failed requests

Build the chart, install it on kind with the prod values into a restricted namespace, release v2 while probe.yaml runs, roll back a v3-broken release, and publish the project with the evidence in its README.

- You need: The shop chart, kind.yaml, probe.yaml and the shop-web images
- You'll have: A public repository with the chart, the probe counts (0 FAIL) and helm history

```sh
$ helm lint ./shop -f shop/values-prod.yaml
$ ./run.sh                      # create the cluster, build, load, install, release, roll back, drain
$ kubectl logs -n shop probe | sort | uniq -c > evidence.txt
$ helm history shop -n shop >> evidence.txt
$ kind delete cluster --name capstone
```

If `uniq -c` shows any FAIL lines, don't hide them: find the cause, fix it, and write what you changed in the
README. That story is worth more in an interview than a clean run.

## Try it

- Run `helm lint` and `helm template` with each values file and count the objects.
- Explain why the prod Deployment has no `replicas:` line.
- Install on kind into a namespace labelled restricted.
- Upgrade to v2 while probe.yaml calls the app, and count the FAIL lines.
- Do the mini mission and put the project on GitHub.

## Quiz

1. Why is maxUnavailable set to 0 in the chart's rolling update strategy?
   - It makes rollouts faster
   - **An old Pod is removed only after a new one is ready, so capacity never drops during a release** (answer)
   - It disables rollbacks
   Why: With maxSurge 1 and maxUnavailable 0, Kubernetes adds one new Pod, waits for its readiness probe, then removes one old Pod.

2. The prod render has a HorizontalPodAutoscaler and no replicas line in the Deployment. Why?
   - It's a bug in the chart
   - **When autoscaling is on, the HPA owns the replica count; a fixed replicas value would be reset on every helm upgrade** (answer)
   - Prod always runs one replica
   Why: The starter chart leaves replicas out when autoscaling.enabled is true, so Helm and the HPA don't fight.

3. You change GREETING in the values. Why do the Pods restart on the next upgrade?
   - Helm always restarts Pods
   - **The checksum/config annotation changes with the ConfigMap's content, which changes the Pod template** (answer)
   - ConfigMaps restart Pods automatically
   Why: Pods don't reread environment variables from a ConfigMap. Changing an annotation in the Pod template triggers a normal rolling update.

4. Dev renders no PodDisruptionBudget. Why is that deliberate?
   - Dev doesn't support PDBs
   - **Dev runs one replica, and a PDB on a single replica would block every node drain** (answer)
   - PDBs cost money
   Why: Lesson 11 showed a drain blocked by a budget that allowed zero disruptions. With one replica, any budget does that.

## Resources

- [Helm chart best practices](https://helm.sh/docs/chart_best_practices/) (Helm)
- [Production best practices checklist](https://kubernetes.io/docs/setup/best-practices/) (Kubernetes)
- [kind quick start](https://kind.sigs.k8s.io/docs/user/quick-start/) (kind)
- [EKS best practices guide](https://docs.aws.amazon.com/eks/latest/best-practices/introduction.html) (AWS Docs)
