Module 7: Kubernetes — The Complete Guide
Goal
Kubernetes (K8s) is the industry-standard container orchestrator — it runs containers across a fleet of machines, heals failures, scales automatically, and rolls out updates with zero downtime. This is the most heavily-tested skill in DevOps interviews. Everything from Modules 4–6 converges here.
1. Why Kubernetes Exists
Docker Compose runs your stack on one machine. Now answer these at company scale:
- The machine dies at 3 AM — who restarts the containers elsewhere?
- Traffic spikes 10× — who adds instances and load-balances them?
- You deploy v2 — who does the rolling replacement and rollback across 30 servers?
- 50 microservices on 40 machines — who decides what runs where?
Kubernetes answers all of these with one idea: declarative desired state. You tell the cluster "I want 3 replicas of myapp:v2 with these resources" (in YAML), and controllers continuously work to make reality match. A node dies → pods are rescheduled elsewhere automatically. This reconciliation loop is the single most important concept in Kubernetes.
Analogy
Kubernetes is a thermostat, not a light switch. A switch is imperative — you flip it on, and if the bulb blows, the room goes dark and stays dark. A thermostat is declarative: you set 21 degrees and walk away, and the system keeps nudging reality toward that number forever, firing the heater when it drifts. You never say "turn the heater on for 12 minutes" — you state the goal and trust the loop to hold it.
When NOT to use it: a single small app on one server. K8s has real operational cost — Compose or ECS may be smarter. Engineering judgment matters.
2. Architecture
kube-apiserver — the ONLY entry point (kubectl and every node
talk through it)
etcd — key-value DB holding ALL cluster state
scheduler — picks a node for each pod
controller-manager — reconciliation loops
kubelet — node agent, starts/monitors pods
kube-proxy — Service networking
container runtime — containerd
[pod][pod][pod]
- kube-apiserver — REST API front door;
kubectl, kubelets, controllers all talk through it. - etcd — the cluster's memory. Lose etcd without backup = lose the cluster's state.
- scheduler — for each new pod, picks the best node (resources, affinity rules, taints).
- controller-manager — runs the loops: "desired 3 replicas, see 2 → create 1."
- kubelet — on every node; makes containers described by the API actually run.
- kube-proxy — programs iptables so Service IPs route to pods (Module 4 again!).
Managed offerings (EKS/GKE/AKS) run the control plane for you — in real jobs you mostly manage workloads and nodes, not etcd.
Analogy
The control plane is airport air-traffic control; the worker nodes are the runways and gates. The scheduler is the controller deciding which runway each incoming plane (pod) lands on, etcd is the master flight board recording where everything is, and the kubelet is the ground crew at each gate actually parking the planes. Lose the flight board with no backup and the whole airport forgets what's in the air — which is why etcd backups matter so much.
Local playground
# kind = Kubernetes IN Docker — free, disposable clusters
kind create cluster --name dev
kubectl cluster-info
kubectl get nodes(Alternatives: minikube, k3s. All fine.)
3. Pods — The Atom
A pod = one or more containers sharing a network namespace (one IP, can talk over localhost) and volumes. Usually one app container per pod; extra "sidecar" containers handle logging/proxying.
Analogy
A pod is a single flight, not a plane. The main container is the passenger jet; sidecars are the escort vehicles that always taxi with it — the fuel truck, the baggage cart. They move as one unit, share the same gate (network and storage), and if the flight is cancelled the whole convoy goes with it. You schedule flights, never lone escort trucks.
# pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: myapp
labels: { app: myapp }
spec:
containers:
- name: myapp
image: myorg/myapp:v2.3.1
ports: [{ containerPort: 8080 }]
env:
- name: APP_ENV
value: production
resources:
requests: { cpu: 100m, memory: 128Mi } # scheduler reserves this
limits: { cpu: 500m, memory: 256Mi } # hard ceiling (OOMKilled above)kubectl apply -f pod.yaml
kubectl get pods -o wide # status + node + pod IP
kubectl describe pod myapp # EVENTS at the bottom = your debugging goldmine
kubectl logs -f myapp
kubectl exec -it myapp -- sh
kubectl port-forward pod/myapp 8080:8080 # tunnel for local testing
kubectl delete pod myappPod lifecycle: Pending (no node yet / pulling image) → Running → Succeeded/Failed. Restart-related states you must recognize: CrashLoopBackOff (app keeps dying — read kubectl logs --previous), ImagePullBackOff (bad image name/tag or missing registry credentials), OOMKilled (exceeded memory limit — same exit 137 from Module 5).
Probes — how K8s knows your app's real state:
livenessProbe: # fails → restart the container
httpGet: { path: /health, port: 8080 }
periodSeconds: 10
readinessProbe: # fails → remove from Service traffic (no restart)
httpGet: { path: /ready, port: 8080 }
periodSeconds: 5Liveness = "am I alive?"; readiness = "can I take traffic right now?" (e.g., still warming caches). Mixing them up causes restart storms — a classic production mistake.
Pods are mortal and disposable — you almost never create bare pods. You create controllers that manage pods:
4. Deployments — How Apps Actually Ship
A Deployment manages a ReplicaSet which manages N identical pods, and handles rolling updates.
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 3
selector:
matchLabels: { app: myapp }
strategy:
type: RollingUpdate
rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } # zero-downtime
template: # ← pod template (everything from §3 goes here)
metadata:
labels: { app: myapp }
spec:
containers:
- name: myapp
image: myorg/myapp:v2.3.1
ports: [{ containerPort: 8080 }]
readinessProbe:
httpGet: { path: /health, port: 8080 }kubectl apply -f deployment.yaml
kubectl get deploy,rs,pods # see the whole hierarchy
kubectl scale deploy myapp --replicas=5
kubectl set image deploy/myapp myapp=myorg/myapp:v2.4.0 # triggers rolling update
kubectl rollout status deploy/myapp
kubectl rollout history deploy/myapp
kubectl rollout undo deploy/myapp # ONE-COMMAND ROLLBACK Rolling update mechanics: new ReplicaSet created → one new pod comes up → passes readiness → one old pod terminated → repeat. Users never notice. rollout undo re-activates the previous ReplicaSet — this is the rollback story CI/CD dreamed of.
Analogy
A rolling update is swapping every plane in a fleet for a newer model without ever grounding the airline. One new jet is brought online and cleared as flight-ready before a single old one is retired, so there are always enough planes in the air to carry passengers. And rollout undo is the airline keeping the old fleet fuelled on the apron — if the new model misbehaves, they're flying again within minutes.
Deployment strategies at K8s level: Rolling (built-in, default), Recreate (strategy.type: Recreate — downtime, for apps that can't run two versions), Blue/Green and Canary (achieved with two Deployments + Service/Ingress traffic shifting, or tools like Argo Rollouts).
Other workload controllers
| Kind | Guarantees | Use for |
|---|---|---|
| DaemonSet | exactly one pod per node | log shippers, node monitoring agents (you'll use this in Module 10) |
| StatefulSet | stable names (db-0, db-1), stable per-pod storage, ordered startup | databases, Kafka, anything with identity |
| Job / CronJob | run-to-completion / on schedule | migrations, backups, reports |
5. Services & DNS — Stable Networking for Mortal Pods
Pods die and get new IPs constantly. A Service gives a stable virtual IP + DNS name that load-balances across pods selected by labels:
apiVersion: v1
kind: Service
metadata:
name: myapp
spec:
selector: { app: myapp } # any pod with this label is a backend
ports:
- port: 80 # service port
targetPort: 8080 # container port
type: ClusterIP # default: internal-onlyCluster DNS: any pod can now reach http://myapp (same namespace) or http://myapp.production.svc.cluster.local. Your DATABASE_URL becomes postgres://db:5432 — identical to Compose, now cluster-wide.
Analogy
A Service is the airport's single published phone number for a whole department, not any one employee's mobile. Staff (pods) are hired and fired constantly and their personal numbers (pod IPs) change daily, but callers always dial the one department line and get routed to whoever is on duty. That stable line is what lets everything else stop caring which specific pod is alive right now.
Service types:
- ClusterIP — internal only (databases, internal APIs). Default and most common.
- NodePort — opens a high port (30000–32767) on every node. Dev/demo use.
- LoadBalancer — cloud provisions a real LB (AWS ELB) pointing at the service. One cloud LB per service = expensive → hence Ingress.
6. Ingress & Gateway API — HTTP Routing In
Ingress = one entry point (one cloud LB) routing HTTP by host/path to many services:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: main
annotations:
cert-manager.io/cluster-issuer: letsencrypt # automatic TLS certs
spec:
ingressClassName: nginx
rules:
- host: myapp.com
http:
paths:
- path: /api
pathType: Prefix
backend: { service: { name: api, port: { number: 80 } } }
- path: /
pathType: Prefix
backend: { service: { name: frontend, port: { number: 80 } } }
tls:
- hosts: [myapp.com]
secretName: myapp-tlsIngress is only a spec — an ingress controller (nginx-ingress, Traefik, AWS ALB controller) must be installed to implement it. Install nginx-ingress via Helm, point DNS at its LoadBalancer service, and every future app is just another Ingress rule.
Gateway API is the modern successor: role-separated resources (GatewayClass → infra team, Gateway → platform team, HTTPRoute → app teams), native traffic-splitting (canary: 90/10 between two services), TCP/gRPC routing — all standard fields instead of controller-specific annotations. New platforms increasingly choose it; know both.
7. Configuration: ConfigMaps & Secrets
Config lives outside images (build once, configure per environment):
kubectl create configmap app-config --from-literal=LOG_LEVEL=info
kubectl create secret generic db-cred --from-literal=password='S3cr3t!' envFrom:
- configMapRef: { name: app-config }
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef: { name: db-cred, key: password }K8s Secrets are only base64-encoded, not encrypted by default — anyone with API read access sees them. Production hardening: enable encryption at rest, restrict with RBAC, or integrate External Secrets Operator/Vault/AWS Secrets Manager. Never commit secret manifests to Git (that's what sealed-secrets/SOPS solve).
8. Storage: PV & PVC
- PersistentVolume (PV) — a piece of actual storage (EBS disk, NFS share).
- PersistentVolumeClaim (PVC) — a pod's request for storage ("give me 10Gi read-write").
- StorageClass — enables dynamic provisioning: a PVC automatically creates a cloud disk.
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: pgdata }
spec:
accessModes: [ReadWriteOnce] # one node at a time (typical block storage)
storageClassName: gp3 # AWS EBS class on EKS
resources: { requests: { storage: 10Gi } }
---
# in the pod spec:
volumeMounts: [{ name: data, mountPath: /var/lib/postgresql/data }]
volumes:
- name: data
persistentVolumeClaim: { claimName: pgdata }The claim/volume separation means app manifests are portable — the same PVC YAML works on EKS (EBS), GKE (PD), or on-prem (NFS); only the StorageClass differs.
9. Scheduling Controls & Autoscaling
Steer where pods land:
nodeSelector: { disktype: ssd } # simplest: label match
# nodeAffinity: richer expressions (In/NotIn, preferred vs required)
# podAntiAffinity: spread replicas across nodes/AZs for HATaints & tolerations — the inverse: a node repels pods unless they tolerate it:
kubectl taint nodes gpu-node1 gpu=true:NoSchedule # nothing schedules here... tolerations: # ...except pods that opt in
- { key: gpu, operator: Equal, value: "true", effect: NoSchedule }Real uses: reserving GPU nodes, keeping workloads off control-plane nodes, draining for maintenance (kubectl drain node1).
HPA — Horizontal Pod Autoscaler (requires metrics-server + resource requests set):
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: myapp }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: myapp }
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource: { name: cpu, target: { type: Utilization, averageUtilization: 70 } }Traffic spike → CPU crosses 70% → HPA adds pods → readiness gates them in → Service spreads load. Pair with cluster-autoscaler (adds nodes when pods can't fit) for full elasticity.
Analogy
The autoscaler is the same thermostat idea applied to crowds instead of heat. You set "keep CPU around 70 percent" the way you'd set a target temperature, and when the lunchtime rush pushes the room over that line, the HPA opens more checkout lanes (pods) automatically; when the crowd thins, it closes them. Cluster-autoscaler is the manager who adds whole new floors (nodes) when even every lane open isn't enough.
10. Security: RBAC, Service Accounts, Network Policies
RBAC — who may do what:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role # namespaced (ClusterRole = cluster-wide)
metadata: { name: pod-reader, namespace: production }
rules:
- apiGroups: [""]
resources: [pods, pods/log]
verbs: [get, list, watch]
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata: { name: devs-read-pods, namespace: production }
subjects: [{ kind: Group, name: developers, apiGroup: rbac.authorization.k8s.io }]
roleRef: { kind: Role, name: pod-reader, apiGroup: rbac.authorization.k8s.io }Now developers can view logs in production but not delete deployments. Verify with kubectl auth can-i delete deploy -n production --as-group=developers → no. The K8s dashboard should be exposed only with RBAC-scoped tokens (read-only for most humans) — an admin-token dashboard on the internet is a famous breach pattern (Tesla, 2018).
ServiceAccounts — identity for pods (RBAC for software): a CI pod gets an SA allowed to update one Deployment; on EKS, SAs map to IAM roles (IRSA) so pods reach S3 without static keys.
NetworkPolicies — pod-level firewalls (default: everything can talk to everything!):
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: { name: db-only-from-api, namespace: production }
spec:
podSelector: { matchLabels: { app: db } }
policyTypes: [Ingress]
ingress:
- from: [{ podSelector: { matchLabels: { app: api } } }]
ports: [{ port: 5432 }]Only api pods can reach the database — a compromised frontend pod gets connection-refused. (Requires a CNI that enforces policies: Calico, Cilium.)
CRDs & Operators — how K8s extends itself: a CustomResourceDefinition teaches the API new types (kind: Certificate, kind: PostgresCluster), and an operator is a controller reconciling them. cert-manager, Prometheus Operator, external-secrets — modern clusters are full of CRDs. Recognize the pattern: install operator → declare custom resources → operator does the expert work.
11. Helm — The Package Manager
Raw YAML across dev/staging/prod = copy-paste drift. Helm templates manifests and versions releases:
Analogy
Helm is a meal-kit recipe with adjustable portions, not a fixed plated dinner. The chart is the recipe with blanks — "serves {{ replicaCount }}, uses image {{ tag }}" — and values.yaml is the order slip where you write "table of 3, staging portion". One recipe feeds dev, staging, and prod by swapping the order slip, instead of writing out three nearly-identical menus by hand and letting them drift apart.
helm create mychart # scaffold
helm install myapp ./mychart -f values-prod.yaml # deploy
helm upgrade myapp ./mychart --set image.tag=v2.4.0 # release new version
helm history myapp
helm rollback myapp 1 # versioned rollback
# consuming public charts:
helm repo add bitnami https://charts.bitnami.com/bitnami
helm install db bitnami/postgresql -n data --create-namespaceOne chart + three values files (values-dev/staging/prod.yaml) replaces three YAML forests. Installing complex software (Prometheus stack, nginx-ingress, Grafana) is one helm install instead of 40 manifests — this is how you'll set up Module 10.
12. Deploying a Service A→Z (The Interview Walkthrough)
Be able to narrate this cold:
- CI builds and pushes
myorg/api:v2.4.0(Modules 5–6). - Namespace per env:
kubectl create ns production. - Apply/
helm upgrade: Deployment (3 replicas, probes, resources), ClusterIP Service, ConfigMap+Secret, Ingress with TLS, HPA, NetworkPolicy. - DNS:
api.myapp.com→ ingress controller's LB. - Verify:
kubectl rollout status,kubectl get pods -o wide,curl https://api.myapp.com/health. - Bad release?
helm rollback/kubectl rollout undo— seconds.
Debugging cheatsheet (live near this)
kubectl get events -n prod --sort-by=.lastTimestamp # what just happened
kubectl describe pod <p> # scheduling/probe/image issues
kubectl logs <p> --previous # the crash BEFORE the restart
kubectl exec -it <p> -- sh # poke inside
kubectl get endpoints myapp # empty? selector/readiness mismatch!
kubectl top pods # resource hogs
kubectl run tmp --rm -it --image=busybox -- sh # throwaway debug pod (test DNS, nc)The #1 real-world gotcha: Service has no endpoints — label selector typo or all pods failing readiness. kubectl get endpoints reveals it instantly.
13. Hands-On Project (Do This)
On a kind cluster, deploy your Modules 5–6 app the K8s way:
- Deployment (3 replicas, both probes, requests/limits) + ClusterIP Service; ConfigMap for settings, Secret for DB password.
- Postgres as a StatefulSet with a PVC; Redis as a Deployment. Prove data survives pod deletion.
- Install nginx-ingress via Helm; route
api.localtest.meto your service. - Roll out v2 with
kubectl set image, watchrollout status, thenrollout undo. - Add HPA (install metrics-server), generate load with
ab, watch pods scale. - Break things deliberately and diagnose: wrong image tag (ImagePullBackOff), failing readiness path (endpoints empty), memory limit 32Mi (OOMKilled), selector typo (no endpoints).
- Add a NetworkPolicy so only the api can reach Postgres; verify with a busybox pod.
- Package everything as a Helm chart with dev/prod values; add a GitHub Actions job that runs
helm upgrade --installagainst the cluster (orhelm template+ kubeconform for CI validation). - RBAC: create a read-only Role+RoleBinding and verify with
kubectl auth can-i.
14. Self-Check Questions
- Explain the reconciliation loop. What happens, step by step, when a node dies?
- Liveness vs readiness probe — and the failure mode of confusing them?
- Why do Services exist if pods have IPs? What does empty
kubectl get endpointstell you? - ClusterIP vs NodePort vs LoadBalancer vs Ingress — when each?
- CrashLoopBackOff vs ImagePullBackOff vs OOMKilled — causes and first command for each?
- Deployment vs StatefulSet vs DaemonSet — one example workload each.
- Why are K8s Secrets "not really secret" by default, and two hardening options?
- What problem does Helm solve over raw YAML? What does
helm rollbackactually do?
Next → Module 8: Public Cloud (AWS)
