Lesson 7: Kubernetes and Container Orchestration
Lesson opener
In one line: Kubernetes automates the scheduling, scaling, self-healing, and rolling updates of containerised workloads — but it is a significant operational investment that only pays off at the right scale.
Why it matters: Northline runs over 30 microservices. Without an orchestrator, the platform team would spend their days manually restarting crashed containers, balancing traffic across servers, and scripting deployments. Kubernetes handles all of that, consistently, at 03:00 without waking anyone up.
Before this lesson: You must understand containers and images (#devops6), deployment strategies (#devops5), and basic cloud networking (#cloud1). Familiarity with YAML and kubectl commands is helpful. If you have not installed Docker Desktop, do that first (#setup8).
Learning objectives
By the end of this lesson you will be able to:
- Describe the Kubernetes cluster model: nodes, the control plane, and the kubelet.
- Write and apply a Deployment, Service, and ConfigMap manifest.
- Configure liveness and readiness probes correctly.
- Set CPU and memory requests and limits for a Pod.
- Perform and roll back a rolling update using
kubectl. - Distinguish ConfigMaps from Secrets and handle Secrets safely.
- Explain core Kubernetes security controls: non-root enforcement, read-only root filesystem, and network policies.
- Identify workloads where Kubernetes is not the appropriate runtime choice.
Lesson deliverable: A set of Kubernetes manifests (Deployment, Service, ConfigMap, and a basic Secret reference) for the Northline billing-api service, with a written rationale for probe and resource limit choices.
Prerequisites
| Concept | Where covered |
|---|---|
| Container images and Dockerfiles | #devops6 |
| Deployment strategies and rollback | #devops5 |
| Cloud environments and networking | #cloud1, #cloud8 |
| Secrets management | #cyber5, #cyber9 |
| Observability and alerting | #sad5, #sad7 |
Plain English: what is Kubernetes really doing?
Imagine a hotel with 50 rooms and 200 guests checking in. You need a concierge system that assigns guests to rooms, moves guests if a room breaks down, ensures the restaurant is never overwhelmed, and upgrades rooms one floor at a time without disturbing guests.
Kubernetes is that concierge system for containers. You describe what you want (three copies of the billing API, each with 256 MB of memory, always available) and Kubernetes figures out where to run them, when to restart them if they crash, and how to shift traffic during an update.
The cluster model
A cluster consists of:
- Control plane: The brain. Stores cluster state in
etcd, schedules Pods onto nodes, manages rollouts, and exposes the Kubernetes API. - Worker nodes: The rooms. Each node runs a
kubelet(the room agent), a container runtime (Docker or containerd), and a network proxy (kube-proxy). - Pod: The smallest schedulable unit. Usually one container per Pod. Pods are ephemeral — when one dies, Kubernetes creates a replacement, possibly on a different node.
- Deployment: A controller that declares how many Pod replicas to run and manages rolling updates.
- Service: A stable network address in front of a set of Pods. Pods come and go; the Service IP stays the same.
- Ingress: A layer-7 (HTTP) routing resource that maps hostnames and paths to Services. Northline's cluster uses an ingress controller (NGINX or cloud-managed) to handle TLS termination and routing from the internet. ⚠️ Ingress controller availability and configuration are environment-dependent; confirm with the platform team.
Walkthrough: deploying the Northline billing-api
Business objective
Run three replicas of billing-api:2.3.0 in the billing namespace. The service must:
- Automatically restart if it crashes.
- Refuse traffic until it is truly ready.
- Roll out updates without any request failures.
- Stay within defined CPU and memory limits to avoid starving neighbours.
- Read its database URL from a Secret (never from a ConfigMap or environment variable baked into the image).
Owners
| Role | Responsibility |
|---|---|
| Platform engineer | Cluster administration, namespace setup, network policies |
| Backend engineer | Writes and maintains manifests for the service |
| Security engineer | Reviews SecurityContext, network policies, Secret access (#cyber9) |
| SRE | Sets resource limits, monitors probes and pod disruption budgets (#sad7) |
Namespace and RBAC
apiVersion: v1
kind: Namespace
metadata:
name: billing
labels:
environment: productionEvery Northline service gets its own namespace. RBAC roles are namespace-scoped: the billing team can deploy to billing but cannot read Secrets in payments. This is the Kubernetes equivalent of least-privilege (#cyber5).
ConfigMap: non-sensitive configuration
apiVersion: v1
kind: ConfigMap
metadata:
name: billing-api-config
namespace: billing
data:
LOG_LEVEL: "info"
FEATURE_FLAG_ENDPOINT: "http://flagd.internal:8013"
MAX_INVOICE_BATCH: "500"ConfigMaps hold non-sensitive configuration. Do not put database URLs, API keys, or tokens in a ConfigMap — they are stored unencrypted in etcd and visible to anyone with kubectl get configmap access in the namespace.
Secret: sensitive configuration
Kubernetes Secrets are base64-encoded by default — not encrypted. At Northline, etcd encryption at rest is enabled and Secrets are backed by the cloud secrets manager (#cloud11) via the External Secrets Operator. ⚠️ Whether your cluster has encryption at rest enabled is environment-dependent. Confirm before storing any secret in a native Kubernetes Secret.
# This Secret is managed by External Secrets Operator — do not edit manually.
# The actual value comes from the cloud secrets manager.
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: billing-db-credentials
namespace: billing
spec:
refreshInterval: 1h
secretStoreRef:
name: northline-secret-store
kind: ClusterSecretStore
target:
name: billing-db-credentials
data:
- secretKey: DATABASE_URL
remoteRef:
key: billing/prod/database-urlDeployment manifest
apiVersion: apps/v1
kind: Deployment
metadata:
name: billing-api
namespace: billing
labels:
app: billing-api
version: "2.3.0"
spec:
replicas: 3
selector:
matchLabels:
app: billing-api
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # Allow 1 extra pod during rollout
maxUnavailable: 0 # Never reduce below 3 during rollout
template:
metadata:
labels:
app: billing-api
version: "2.3.0"
spec:
securityContext:
runAsNonRoot: true # Cluster-level enforcement: reject root containers
runAsUser: 1001
runAsGroup: 1001
fsGroup: 1001
seccompProfile:
type: RuntimeDefault # Syscall filtering
containers:
- name: billing-api
image: registry.northline.internal/billing-api:2.3.0
imagePullPolicy: Always # Always pull; never use :latest in production
ports:
- containerPort: 8000
envFrom:
- configMapRef:
name: billing-api-config
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: billing-db-credentials
key: DATABASE_URL
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 15
periodSeconds: 20
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
periodSeconds: 10
failureThreshold: 3
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp-vol
mountPath: /tmp # Writable scratch space when root FS is read-only
volumes:
- name: tmp-vol
emptyDir: {}Probes explained
| Probe | Question it answers | Failure consequence |
|---|---|---|
| Liveness | Is the process alive and not stuck in a deadlock? | Pod is restarted |
| Readiness | Is the pod ready to serve traffic right now? | Pod removed from Service endpoints; no restart |
| Startup (optional) | Has a slow-starting application finished initialising? | Delays liveness/readiness checks until it passes |
A common mistake is to make the liveness probe check external dependencies (database connectivity). If the database is down, Kubernetes will endlessly restart healthy pods rather than preserving them. The liveness probe should check only that the process itself is functioning. The readiness probe is the right place to check dependency health.
Resource requests and limits
- Request: The minimum guaranteed resources. The scheduler uses this to decide which node to place the Pod on.
- Limit: The maximum allowed. Exceeding the memory limit kills the Pod (OOMKilled). Exceeding the CPU limit throttles the Pod.
Setting limits without requests (or setting them equal) is the safe default. Never set memory limits below what the application needs under normal load — measure in staging first.
Service manifest
apiVersion: v1
kind: Service
metadata:
name: billing-api
namespace: billing
spec:
selector:
app: billing-api
ports:
- port: 80
targetPort: 8000
type: ClusterIP # Internal-only; Ingress handles external trafficClusterIP means the Service is only reachable within the cluster. External traffic arrives via an Ingress resource (or an API gateway, depending on Northline's architecture). This separation limits the external attack surface (#cyber9).
Rolling update and rollback
# Update the image version
kubectl set image deployment/billing-api billing-api=registry.northline.internal/billing-api:2.4.0 -n billing
# Monitor the rollout
kubectl rollout status deployment/billing-api -n billing
# Roll back if something goes wrong
kubectl rollout undo deployment/billing-api -n billing
# Check rollout history
kubectl rollout history deployment/billing-api -n billingWith maxUnavailable: 0, no pods are removed until the new pod is ready (passes its readiness probe). This prevents any request from reaching an unready pod during the rollout.
Security baseline: what Northline enforces
| Control | Manifest field | Purpose |
|---|---|---|
| Non-root | runAsNonRoot: true | Enforced at cluster level via admission controller |
| No privilege escalation | allowPrivilegeEscalation: false | Prevents sudo-style escalation inside container |
| Read-only root filesystem | readOnlyRootFilesystem: true | Prevents malware writing to the container filesystem |
| Drop all capabilities | capabilities.drop: ["ALL"] | Removes Linux capabilities not needed by the app |
| Seccomp profile | seccompProfile: RuntimeDefault | Filters system calls; reduces kernel attack surface |
These controls are enforced by a Pod Security Admission policy at the namespace level. A manifest that violates them is rejected at apply time, not discovered post-deploy.
When Kubernetes is NOT the right answer
Kubernetes is genuinely powerful, but it introduces real operational complexity. Consider simpler alternatives when:
| Situation | Better alternative |
|---|---|
| Single-service hobby project or proof of concept | Docker Compose, a PaaS (Heroku, Railway, Fly.io) |
| Batch job that runs once a day | Cloud-managed job service (AWS Batch, Cloud Run Jobs) |
| Static site or frontend-only application | CDN + object storage |
| Team has no one with Kubernetes operational expertise | Managed container service (Cloud Run, App Runner, Azure Container Apps) |
| GPU-intensive ML training | Bare metal or specialised ML platform (#mlops\*) |
A managed container service gives you many Kubernetes benefits (auto-scaling, rolling deploys, health checks) without the control-plane management overhead. Northline uses Kubernetes for its core platform and managed container services for low-traffic or ephemeral workloads. The right answer depends on scale, team expertise, and operational cost (#cloud8, #sad9).
Network policies
By default, all pods in a Kubernetes cluster can communicate with all other pods. This violates the principle of least privilege (#cyber5). Northline enforces network policies that restrict pod-to-pod communication to explicitly declared flows:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: billing-api-ingress
namespace: billing
spec:
podSelector:
matchLabels:
app: billing-api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: ingress-controller # Only the ingress controller may reach billing-api
ports:
- port: 8000
egress:
- to:
- namespaceSelector:
matchLabels:
name: database # billing-api may only talk to its database namespace
ports:
- port: 5432
- to:
- namespaceSelector:
matchLabels:
name: kube-system # DNS resolution
ports:
- port: 53Without network policies, a compromised pod in any namespace can attempt connections to every other pod in the cluster. Network policies are the Kubernetes equivalent of firewall rules at the application layer.
⚠️ Network policies require a CNI plugin that supports them (e.g., Calico, Cilium). The default kubenet CNI does not enforce network policies. Confirm CNI capability in your cluster before relying on policies.
Worked examples
Example A: Debugging a pod stuck in CrashLoopBackOff
kubectl get pods -n billing
# NAME READY STATUS RESTARTS AGE
# billing-api-7d6b9f4c5-xk2vp 0/1 CrashLoopBackOff 4 3m
kubectl describe pod billing-api-7d6b9f4c5-xk2vp -n billing
# Events show: OOMKilled — memory limit 128Mi exceeded
kubectl logs billing-api-7d6b9f4c5-xk2vp -n billing --previous
# Heap dump lines visible — memory leak in VAT calculation loopFix: increase memory limit to 512Mi after profiling; then investigate the leak. Do not simply raise the limit without understanding the cause.
Example B: Horizontal pod autoscaling
During Northline's end-of-month invoice run, CPU spikes to 90 %. A Horizontal Pod Autoscaler (HPA) scales the deployment from 3 to 10 replicas automatically:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: billing-api-hpa
namespace: billing
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: billing-api
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70⚠️ HPA requires the metrics server to be installed in the cluster. Confirm availability in your environment before relying on it.
Failure chain: the liveness probe that caused a cascade
Database experiences slow queries (P99 latency 4 s)
→ Engineer adds database ping to liveness probe endpoint
→ DB slowness causes liveness probe to time out (5 s threshold)
→ Kubernetes restarts all pods simultaneously
→ All pods fail their startup check (DB still slow)
→ All pods in CrashLoopBackOff: service fully down
→ Without the liveness-DB check, pods would have degraded gracefully
→ Fix: move DB check to readiness probe; liveness checks process health onlyThis failure cascaded a partial degradation into a complete outage. The distinction between liveness and readiness probes is not academic — it has real consequences.
Guided exercise
Scenario: A new Northline service notifications-api runs as root and has no resource limits. The security team has raised a finding. The image is registry.northline.internal/notifications-api:1.2.0.
Step 1: Write a Deployment manifest that:
- Runs 2 replicas.
- Enforces non-root (UID 1002).
- Sets requests of 100m CPU / 128Mi memory and limits of 200m CPU / 256Mi memory.
- Has a readiness probe on
/readyport 8080. - Has a liveness probe on
/healthzport 8080.
Step 2: The service writes a temporary file to /app/tmp during processing. The manifest uses readOnlyRootFilesystem: true. How do you accommodate this?
Step 3: After deploying, a pod is in Pending state. kubectl describe pod shows Insufficient memory. What are the two most likely causes and how do you investigate?
Solution
Step 1: Deployment manifest (abbreviated):
spec:
replicas: 2
template:
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1002
runAsGroup: 1002
containers:
- name: notifications-api
image: registry.northline.internal/notifications-api:1.2.0
resources:
requests:
cpu: "100m"
memory: "128Mi"
limits:
cpu: "200m"
memory: "256Mi"
livenessProbe:
httpGet:
path: /healthz
port: 8080
initialDelaySeconds: 10
periodSeconds: 20
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 10
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: tmp-vol
mountPath: /app/tmp
volumes:
- name: tmp-vol
emptyDir: {}Step 2: Mount an emptyDir volume at /app/tmp. emptyDir is ephemeral (destroyed when the Pod is deleted) and writable, while the root filesystem remains read-only.
Step 3: Causes: (a) Memory request is larger than any node's available allocatable memory — check kubectl describe nodes for allocatable memory versus current requests. (b) All nodes are at capacity — the cluster may need to scale out a node group. Fix path: reduce the memory request if it is over-provisioned, or trigger cluster autoscaler to add a node.
Independent exercise
Task: Write a complete set of Kubernetes manifests for a Northline audit-logger service that:
- Runs as a singleton (1 replica) — only one instance must run at a time.
- Reads audit events from a Redis queue (Redis URL from a Secret).
- Writes to an output directory mounted from a PersistentVolumeClaim (PVC).
- Must restart automatically if the process deadlocks.
- Must not serve traffic during startup (takes 45 seconds to load reference data).
Acceptance criteria:
- [ ] Deployment with 1 replica and appropriate update strategy to avoid two instances running simultaneously.
- [ ] Liveness probe detects deadlock (process health only, not Redis health).
- [ ] Readiness probe prevents traffic until the 45-second startup completes (use
startupProbeor appropriateinitialDelaySeconds). - [ ] PVC mounted as a volume (definition can be a placeholder
# PVC defined separately). - [ ] Redis URL injected from a Secret reference (not hardcoded).
- [ ] Non-root security context applied.
- [ ] Written explanation of why liveness and readiness thresholds were chosen.
Common mistakes
| Mistake | Consequence | Prevention |
|---|---|---|
Using :latest image tag in production | Unpredictable deploys; no rollback path | Always use a specific digest or semver tag |
| Putting DB health in liveness probe | Cascade outage when DB is slow | Liveness = process health only; readiness = dependency health |
| No resource requests | Noisy-neighbour problem; scheduler cannot place pods optimally | Always set requests; measure in staging |
No maxUnavailable: 0 for critical services | Requests dropped during rolling update | Set maxUnavailable: 0 and maxSurge: 1 for zero-downtime |
| Storing real secrets in ConfigMap | Unencrypted in etcd; visible to all namespace readers | Use Secrets (with etcd encryption) or External Secrets Operator |
| Running privileged containers without justification | Root-equivalent access on the host | Enforce via PodSecurity admission; require security review for any exception |
Quick checks
Q1: What is the difference between a Pod and a Deployment?
A: A Pod is a single running instance (ephemeral). A Deployment is a controller that declares how many Pod replicas to run and manages rolling updates and self-healing — if a Pod dies, the Deployment creates a replacement.
Q2: Why should the liveness probe not check database connectivity?
A: If the database is slow or temporarily unavailable, the liveness probe fails and Kubernetes restarts the pod — making a partial degradation into a complete outage. The liveness probe should only verify the process is alive. Use readiness for dependency health.
Q3: What is the difference between a resource request and a resource limit?
A: A request is the minimum guaranteed amount; the scheduler uses it for placement. A limit is the maximum allowed; exceeding the memory limit causes the pod to be OOMKilled.
Q4: Name two situations where Kubernetes is not the appropriate choice.
A: Any two from: single-service hobby project, once-a-day batch job, static site, team without K8s expertise, GPU-intensive ML training. (See the "When not to use K8s" table.)
Q5: What does readOnlyRootFilesystem: true protect against?
A: It prevents malware or an attacker (who has achieved code execution) from writing files to the container filesystem — for example, dropping a reverse shell script. It also ensures any temporary writes are intentional and use explicitly mounted volumes.
Quiz alignment
| Quiz question | Lesson section |
|---|---|
| Cluster model components | Plain English |
| Probe types and failure consequences | Walkthrough → Probes table |
| Rolling update mechanics | Walkthrough → Rolling update |
| When not to use Kubernetes | Plain English → "Not the answer" table |
| Security context fields | Walkthrough → Security baseline |
Takeaways
- Kubernetes describes desired state; the control plane continuously reconciles reality to match it.
- Use readiness probes to gate traffic; use liveness probes to detect deadlocks. Never conflate the two.
- Resource requests and limits are not optional — they protect your workload and your neighbours.
- Non-root, read-only filesystem, dropped capabilities, and seccomp are the Northline security baseline, not optional hardening.
- Kubernetes adds real operational complexity. Evaluate simpler managed runtimes for low-scale or ephemeral workloads.
- Rollback is one command (
kubectl rollout undo), but it only works if you used specific image tags and did not make breaking database changes.
Bridge to next lesson
You can now deploy and manage containerised workloads. But who created the cluster, the namespace, the network policies, and the secrets store? The next lesson (#devops8) answers that: Infrastructure as Code — the practice of defining every cloud resource in version-controlled, reviewable, auditable configuration files so that environments are reproducible, consistent, and never a mystery.