Rana Maninder Singh
Lesson 7 of 12DevOps & Platform Engineering

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:

  1. Describe the Kubernetes cluster model: nodes, the control plane, and the kubelet.
  2. Write and apply a Deployment, Service, and ConfigMap manifest.
  3. Configure liveness and readiness probes correctly.
  4. Set CPU and memory requests and limits for a Pod.
  5. Perform and roll back a rolling update using kubectl.
  6. Distinguish ConfigMaps from Secrets and handle Secrets safely.
  7. Explain core Kubernetes security controls: non-root enforcement, read-only root filesystem, and network policies.
  8. 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

ConceptWhere 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:


Walkthrough: deploying the Northline billing-api

Business objective

Run three replicas of billing-api:2.3.0 in the billing namespace. The service must:

Owners

RoleResponsibility
Platform engineerCluster administration, namespace setup, network policies
Backend engineerWrites and maintains manifests for the service
Security engineerReviews SecurityContext, network policies, Secret access (#cyber9)
SRESets resource limits, monitors probes and pod disruption budgets (#sad7)

Namespace and RBAC

apiVersion: v1
kind: Namespace
metadata:
  name: billing
  labels:
    environment: production

Every 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-url

Deployment 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

ProbeQuestion it answersFailure consequence
LivenessIs the process alive and not stuck in a deadlock?Pod is restarted
ReadinessIs 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

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 traffic

ClusterIP 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 billing

With 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

ControlManifest fieldPurpose
Non-rootrunAsNonRoot: trueEnforced at cluster level via admission controller
No privilege escalationallowPrivilegeEscalation: falsePrevents sudo-style escalation inside container
Read-only root filesystemreadOnlyRootFilesystem: truePrevents malware writing to the container filesystem
Drop all capabilitiescapabilities.drop: ["ALL"]Removes Linux capabilities not needed by the app
Seccomp profileseccompProfile: RuntimeDefaultFilters 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:

SituationBetter alternative
Single-service hobby project or proof of conceptDocker Compose, a PaaS (Heroku, Railway, Fly.io)
Batch job that runs once a dayCloud-managed job service (AWS Batch, Cloud Run Jobs)
Static site or frontend-only applicationCDN + object storage
Team has no one with Kubernetes operational expertiseManaged container service (Cloud Run, App Runner, Azure Container Apps)
GPU-intensive ML trainingBare 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: 53

Without 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 loop

Fix: 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 only

This 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:

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:

Acceptance criteria:


Common mistakes

MistakeConsequencePrevention
Using :latest image tag in productionUnpredictable deploys; no rollback pathAlways use a specific digest or semver tag
Putting DB health in liveness probeCascade outage when DB is slowLiveness = process health only; readiness = dependency health
No resource requestsNoisy-neighbour problem; scheduler cannot place pods optimallyAlways set requests; measure in staging
No maxUnavailable: 0 for critical servicesRequests dropped during rolling updateSet maxUnavailable: 0 and maxSurge: 1 for zero-downtime
Storing real secrets in ConfigMapUnencrypted in etcd; visible to all namespace readersUse Secrets (with etcd encryption) or External Secrets Operator
Running privileged containers without justificationRoot-equivalent access on the hostEnforce 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 questionLesson section
Cluster model componentsPlain English
Probe types and failure consequencesWalkthrough → Probes table
Rolling update mechanicsWalkthrough → Rolling update
When not to use KubernetesPlain English → "Not the answer" table
Security context fieldsWalkthrough → Security baseline

Takeaways


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.