What You'll Build
In this exercise you will translate the Docker Compose IPL analytics platform from M2 Exercise into a complete set of Kubernetes manifests, deploying the FastAPI scorecard service, PostgreSQL, and Redis to a local Kubernetes cluster using kind or minikube. You will apply every M3 concept in a single integrated deployment: a dedicated namespace with ResourceQuota and LimitRange, a Deployment with rolling update strategy and readiness/liveness probes, ClusterIP Services for internal communication, a ConfigMap for application configuration, a Secret for database credentials, a PodDisruptionBudget, and topology spread constraints for zone distribution. The verification sequence confirms each Kubernetes property independently — from namespace isolation through Service DNS resolution to rolling update mechanics — using the same principle-traceability discipline established in M1 and M2.
The value of this exercise is not merely translating Compose syntax to Kubernetes YAML — it is making the conceptual mapping explicit: `mem_limit: 256m` becomes `resources.limits.memory: 256Mi`, `healthcheck: test: pg_isready` becomes a `readinessProbe: exec: pg_isready`, `depends_on: condition: service_healthy` becomes an init container, and `--profile dev` becomes a separate `development` namespace. Every Compose decision that you made for a specific reason in M2 has a precise Kubernetes equivalent that you make for the same reason, and recognising that mapping is what allows you to move fluidly between local Compose development and Kubernetes deployment without treating them as conceptually separate environments.
Prerequisites
- A local Kubernetes cluster via kind (`kind create cluster --name ipl-cluster`) or minikube (`minikube start`) — verify with `kubectl cluster-info` before beginning.
- The IPL scorecard container image pushed to a registry accessible from the cluster — for kind, load the image directly with `kind load docker-image ipl-scorecard:latest --name ipl-cluster`; for minikube, use `minikube image load`.
- kubectl v1.29+ installed and configured to point to the local cluster — verify with `kubectl version --client` and `kubectl config current-context`.
- Familiarity with all five M3 reading lessons: the Deployment manifest from Lesson 16, the Service types from Lesson 17, ConfigMaps and Secrets from Lesson 18, and the ResourceQuota/LimitRange pattern from Lesson 19 are all applied directly in this exercise.
- The M2 Exercise `compose.yml` available for reference — you will translate each Compose service definition to its Kubernetes equivalent manifest, documenting the mapping explicitly.
Setup & Project Structure
Organise the Kubernetes manifests in a `k8s/` directory with subdirectories for each concern: `namespace/`, `storage/`, `config/`, `deployments/`, and `services/`. Apply manifests in dependency order: namespace and governance objects first, then ConfigMaps and Secrets, then StatefulSets and Deployments, then Services. This ordering matches the dependency graph of the resources and prevents race conditions where a Deployment tries to mount a ConfigMap that does not yet exist.
# Project structure and cluster setup
mkdir -p k8s/{namespace,storage,config,deployments,services}
# Verify cluster is accessible
kubectl cluster-info
kubectl get nodes -o wide
# For kind: load the local image into the cluster
kind load docker-image localhost:5001/ipl-scorecard:latest --name ipl-cluster
# Confirm the image is available on cluster nodes
kubectl run image-test --image=localhost:5001/ipl-scorecard:latest --image-pull-policy=Never --command -- echo "image available" --restart=Never --namespace default
kubectl wait --for=condition=complete pod/image-test --timeout=30s
kubectl delete pod image-test
echo "Cluster ready. Image accessible. Beginning manifest deployment."
# Directory structure
tree k8s/
# k8s/
# ├── namespace/
# │ ├── namespace.yaml (Namespace + ResourceQuota + LimitRange)
# ├── config/
# │ ├── configmap.yaml (ipl-api-config ConfigMap)
# │ └── secret.yaml (ipl-postgres-secret, ipl-redis-secret)
# ├── storage/
# │ └── postgres-pvc.yaml (PersistentVolumeClaim for PostgreSQL data)
# ├── deployments/
# │ ├── postgres-statefulset.yaml
# │ ├── redis-deployment.yaml
# │ └── ipl-api-deployment.yaml
# └── services/
# ├── postgres-service.yaml (headless for StatefulSet)
# ├── redis-service.yaml (ClusterIP)
# └── ipl-api-service.yaml (ClusterIP)Step 1 — Foundation
Create the namespace governance objects first, then the ConfigMaps and Secrets. These are the foundation that all subsequent workloads depend on: a Deployment that references a non-existent ConfigMap will fail to start, and a namespace without a LimitRange will reject Pods that omit resource requests as soon as the ResourceQuota is applied. The governance objects change infrequently — they are the stable layer of the configuration hierarchy — and committing them to version control before any workload manifests ensures that the cluster's governance baseline is reproducible independently of any application code.
# k8s/namespace/namespace.yaml — namespace + governance bundle
apiVersion: v1
kind: Namespace
metadata:
name: ipl-production
labels:
pod-security.kubernetes.io/enforce: restricted
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: ipl-production-quota
namespace: ipl-production
spec:
hard:
requests.cpu: "4"
requests.memory: 8Gi
limits.cpu: "8"
limits.memory: 16Gi
count/pods: "20"
count/services: "10"
services.nodeports: "0"
---
apiVersion: v1
kind: LimitRange
metadata:
name: ipl-production-limits
namespace: ipl-production
spec:
limits:
- type: Container
default: {cpu: 200m, memory: 256Mi}
defaultRequest: {cpu: 100m, memory: 128Mi}
max: {cpu: "1", memory: 1Gi}
min: {cpu: 50m, memory: 64Mi}
---
# k8s/config/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: ipl-api-config
namespace: ipl-production
data:
LOG_LEVEL: "INFO"
FEATURE_REDIS_STATS: "true"
APP_HOST: "0.0.0.0"
APP_PORT: "8000"
---
# k8s/config/secret.yaml (dev only — use ExternalSecret in production)
apiVersion: v1
kind: Secret
metadata:
name: ipl-postgres-secret
namespace: ipl-production
type: Opaque
stringData: # stringData: plain text, kubectl encodes to base64 automatically
password: "ipl_dev_password_change_in_prod"
database_url: "postgresql://rohit_admin:ipl_dev_password_change_in_prod@ipl-postgres:5432/cricket_stats"
---
kubectl apply -f k8s/namespace/
kubectl apply -f k8s/config/
kubectl get configmap,secret -n ipl-production # confirm both exist before proceedingStep 2 — Core Logic
Deploy PostgreSQL as a StatefulSet (the correct Kubernetes workload for databases with stable identity and persistent storage) and Redis as a Deployment (correct for stateless replicated caches). The PostgreSQL StatefulSet uses a headless Service and a volumeClaimTemplate to provision a PersistentVolumeClaim for each replica automatically. Then deploy the IPL API Deployment with an init container that waits for PostgreSQL readiness — the Kubernetes translation of the Compose `depends_on: condition: service_healthy` pattern. Deploy all four Services and verify connectivity using `kubectl exec` into the API Pod.
# k8s/deployments/postgres-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: ipl-postgres
namespace: ipl-production
spec:
serviceName: ipl-postgres # headless Service name for stable DNS
replicas: 1
selector:
matchLabels:
app: ipl-postgres
template:
metadata:
labels:
app: ipl-postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
env:
- name: POSTGRES_DB
value: cricket_stats
- name: POSTGRES_USER
value: rohit_admin
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: ipl-postgres-secret
key: password
ports:
- containerPort: 5432
resources:
requests: {cpu: 200m, memory: 256Mi}
limits: {cpu: "1", memory: 1Gi}
readinessProbe:
exec:
command: ["pg_isready", "-U", "rohit_admin", "-d", "cricket_stats"]
initialDelaySeconds: 10
periodSeconds: 5
securityContext:
runAsNonRoot: true
runAsUser: 999 # postgres official image UID
readOnlyRootFilesystem: false # postgres writes to /var/lib/postgresql
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql/data
# volumeClaimTemplate: automatically creates a PVC per replica
volumeClaimTemplates:
- metadata:
name: postgres-data
spec:
accessModes: [ReadWriteOnce]
resources:
requests:
storage: 5Gi # adjust for actual data size
---
# k8s/services/postgres-service.yaml — headless: direct Pod DNS
apiVersion: v1
kind: Service
metadata:
name: ipl-postgres
namespace: ipl-production
spec:
clusterIP: None
selector:
app: ipl-postgres
ports:
- port: 5432
---
# k8s/deployments/ipl-api-deployment.yaml (abbreviated — full manifest from Lesson 16)
apiVersion: apps/v1
kind: Deployment
metadata:
name: ipl-api
namespace: ipl-production
annotations:
kubernetes.io/change-cause: "initial deployment from M3 exercise"
spec:
replicas: 2
selector:
matchLabels: {app: ipl-api, tier: backend}
strategy:
type: RollingUpdate
rollingUpdate: {maxSurge: 1, maxUnavailable: 0}
template:
metadata:
labels: {app: ipl-api, tier: backend}
spec:
initContainers:
- name: wait-for-postgres
image: postgres:16-alpine
command: ["sh", "-c",
"until pg_isready -h ipl-postgres -U rohit_admin; do sleep 2; done"]
containers:
- name: ipl-api
image: localhost:5001/ipl-scorecard:latest
imagePullPolicy: Never # kind cluster: image loaded locally
envFrom:
- configMapRef:
name: ipl-api-config
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: ipl-postgres-secret
key: database_url
ports:
- containerPort: 8000
name: http
resources:
requests: {cpu: 100m, memory: 128Mi}
limits: {cpu: "500m", memory: 256Mi}
readinessProbe:
httpGet: {path: /health, port: 8000}
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet: {path: /health, port: 8000}
initialDelaySeconds: 30
periodSeconds: 15
securityContext:
runAsNonRoot: true
runAsUser: 10001
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities: {drop: ["ALL"]}
volumeMounts:
- {name: tmp, mountPath: /tmp}
volumes:
- name: tmp
emptyDir: {sizeLimit: "32Mi"}Step 3 — Integration & Enhancement
Apply all manifests in dependency order, wait for all Pods to reach Ready state, then run the verification sequence that confirms each Kubernetes property independently. Add a PodDisruptionBudget to protect the API Deployment during node maintenance, and test the rolling update workflow by updating the image tag and watching the deployment progress via `kubectl rollout status`.
# Apply manifests in dependency order and verify
# Apply in dependency order
kubectl apply -f k8s/deployments/postgres-statefulset.yaml
kubectl apply -f k8s/services/postgres-service.yaml
kubectl apply -f k8s/deployments/redis-deployment.yaml
kubectl apply -f k8s/services/redis-service.yaml
kubectl apply -f k8s/deployments/ipl-api-deployment.yaml
kubectl apply -f k8s/services/ipl-api-service.yaml
# Wait for all Pods to become Ready
kubectl wait --for=condition=ready pod -l app=ipl-postgres -n ipl-production --timeout=120s
kubectl wait --for=condition=ready pod -l app=ipl-api -n ipl-production --timeout=120s
# ── Verification checklist ─────────────────────────────────────────────────
echo "=== M3 Exercise Verification ==="
# 1. All Pods running and ready
echo -n "1. All Pods ready: "
NOT_READY=$(kubectl get pods -n ipl-production --field-selector=status.phase!=Running -o name 2>/dev/null | wc -l)
[ "$NOT_READY" -eq "0" ] && echo "PASS ✓" || echo "FAIL ✗ ($NOT_READY not running)"
# 2. PostgreSQL headless DNS resolves to Pod IP
echo -n "2. PostgreSQL headless DNS works: "
kubectl exec -n ipl-production $(kubectl get pod -l app=ipl-api -n ipl-production -o name | head -1) -- nslookup ipl-postgres.ipl-production.svc.cluster.local | grep -q "Address" && echo "PASS ✓" || echo "FAIL ✗"
# 3. ConfigMap values injected into API container
echo -n "3. ConfigMap injection works: "
LOG_LEVEL=$(kubectl exec -n ipl-production $(kubectl get pod -l app=ipl-api -n ipl-production -o name | head -1) -- sh -c "echo \$LOG_LEVEL")
[ "$LOG_LEVEL" = "INFO" ] && echo "PASS ✓" || echo "FAIL ✗ (got: $LOG_LEVEL)"
# 4. Secret file-mounted (not as env var)
echo -n "4. Secret mounted as file: "
kubectl exec -n ipl-production $(kubectl get pod -l app=ipl-api -n ipl-production -o name | head -1) -- sh -c "test -f /run/secrets/postgres/password" && echo "PASS ✓" || echo "FAIL ✗"
# 5. ResourceQuota shows usage within limits
echo -n "5. ResourceQuota not exceeded: "
kubectl describe resourcequota ipl-production-quota -n ipl-production | grep -v "EXCEEDED" && echo "PASS ✓" || echo "FAIL ✗"
# 6. Rolling update: change image tag and verify
echo -n "6. Rolling update completes: "
kubectl set image deployment/ipl-api ipl-api=localhost:5001/ipl-scorecard:latest -n ipl-production
kubectl rollout status deployment/ipl-api -n ipl-production --timeout=120s && echo "PASS ✓" || echo "FAIL ✗"
echo "=== Exercise verification complete ===" Step 4 — Testing & Verification
Port-forward the API Service to localhost and run the integration tests from M1 Exercise against the Kubernetes-deployed application to confirm that the containerised workload behaves identically whether orchestrated by Compose or by Kubernetes — validating the principle that the same image runs the same way in any OCI-compliant environment, and that the Kubernetes manifest faithfully encodes the same operational configuration as the Compose file.
# Port-forward and integration test
# Port-forward the API Service to localhost for testing
kubectl port-forward service/ipl-api 8080:8000 -n ipl-production &
PF_PID=$!
sleep 3 # wait for port-forward to establish
# Run API integration tests against Kubernetes-deployed application
echo "Testing Kubernetes-deployed application..."
curl -s http://localhost:8080/health | python3 -m json.tool
# Expected: {"status": "healthy", "service": "ipl-scorecard"}
curl -s http://localhost:8080/batters/rohit_sharma | python3 -m json.tool
# Expected: Rohit Sharma stats JSON
curl -s http://localhost:8080/batters | python3 -c "
import sys, json
data = json.load(sys.stdin)
assert len(data) == 3, f'Expected 3 batters, got {len(data)}'
print('All 3 batters returned ✓')
"
# Run pytest suite against the Kubernetes service (same tests as M1 Exercise)
pip install httpx pytest
BASE_URL=http://localhost:8080 pytest tests/ -v --tb=short
# Expected: 4 passed (same tests pass against K8s as against local Compose)
kill $PF_PID
echo "Kubernetes deployment verified — same tests pass as Compose ✓"
echo ""
echo "Compose-to-Kubernetes mapping summary:"
echo " mem_limit: 256m → resources.limits.memory: 256Mi ✓"
echo " healthcheck: pg_isready → readinessProbe: exec: pg_isready ✓"
echo " depends_on: service_healthy → initContainer: wait-for-postgres ✓"
echo " named volume → StatefulSet volumeClaimTemplate ✓"
echo " user-defined network → Namespace + ClusterIP Services ✓"
echo " profiles: [dev] → separate development namespace ✓" Warning: Never use `imagePullPolicy: Never` in production — it only works for images pre-loaded onto cluster nodes and will cause ImagePullBackOff on any node that does not have the image cached locally. This policy is appropriate only for local kind or minikube development clusters where you have loaded the image directly. In all other environments, use `imagePullPolicy: IfNotPresent` for digest-pinned images (which never change, so pulling is only needed once per node) or `imagePullPolicy: Always` if you use mutable tags (which should be avoided in production). The correct production pattern — digest-pinned image with `IfNotPresent` — combines reproducibility with minimal registry round-trips.
Extension Challenge: Translate the monitoring profile from the M2 Exercise extension into Kubernetes manifests — a Prometheus Deployment with a ConfigMap for `prometheus.yml`, a ServiceMonitor CRD (from the Prometheus Operator) that scrapes the FastAPI `/metrics` endpoint, and a Grafana Deployment backed by a ConfigMap containing the JSON dashboard definition. This exercises Kubernetes ConfigMap volume mounting with multi-key file content, the ServiceMonitor pattern for declarative scrape configuration, and how Kubernetes Deployments replace Compose's monitoring profile pattern with namespace-scoped resource organization.
- Every Compose service definition maps to Kubernetes equivalents: `mem_limit` → `resources.limits`, `healthcheck` → `readinessProbe`, `depends_on: service_healthy` → `initContainer`, named volume → `volumeClaimTemplate`.
- Apply manifests in dependency order: namespace governance first, then ConfigMaps and Secrets, then StatefulSets, then Deployments, then Services — each layer depends on the previous being present.
- PostgreSQL belongs in a StatefulSet with a headless Service and `volumeClaimTemplate`, not a Deployment — StatefulSets provide stable Pod names, ordered operations, and per-replica PVC management that databases require.
- The init container pattern is the Kubernetes translation of `depends_on: condition: service_healthy` — it enforces readiness-based dependency ordering without requiring any Kubernetes-specific application code changes.
- Port-forwarding with `kubectl port-forward service/<name> <local>:<remote>` allows running the same integration test suite against the Kubernetes-deployed application as against the local Compose application, confirming environment equivalence.