Skip to content

Lesson 19 of 24Kubernetes

Kubernetes Workloads and kubectl

Pick the right controller for each job, tune how Deployments roll out, and debug Pending, CrashLoopBackOff and OOMKilled pods with kubectl.

15 min read0/5 questions

It is your second week. A deploy went out an hour ago and Slack says checkout is slow. You run kubectl get pods and see two pods in CrashLoopBackOff, one in Pending, and a nightly report job that seems to have run twice. In From Containers to Kubernetes you met the reconcile loop, a minimal Deployment and the idea of a rolling update. This lesson is the next layer: what is really inside a pod, which controller fits which kind of work, the knobs that decide how a rollout behaves, and the kubectl habits that let you diagnose a broken pod in minutes instead of guessing.

Pods up close

A pod is not just "a container with an IP". It is a small group of containers that share some Linux namespaces and storage, and are always scheduled together on the same node.

  • Shared network. Every container in a pod shares one network namespace: one IP, one port space, one localhost. A sidecar can reach the app on localhost:8000, and two containers in one pod cannot both listen on port 8000.
  • Shared volumes. Containers can mount the same volume. An emptyDir volume lives as long as the pod and is the usual way to hand files from one container to another.
  • Shared fate. The pod is scheduled, scaled and deleted as a unit. If you need to scale two things independently, they belong in separate pods.

Most pods have one container. You add more only when they are tightly coupled. Two patterns cover nearly every case:

  • Init containers run to completion, one after another, before any app container starts. Typical uses: wait for a dependency, render a config file, or copy assets into a shared volume. If one fails, the kubelet retries it and the app never starts.
  • Sidecars run alongside the app for the pod's whole life: a log shipper, a proxy, a credentials refresher. Since Kubernetes 1.33 sidecars are a stable, native feature: you declare them in initContainers with restartPolicy: Always. The kubelet starts them before the app, keeps them running, restarts them if they crash, and stops them after the app has exited, so the log shipper sees the app's last lines.
k8s/api-pod-template.yaml
spec:
  initContainers:
    - name: wait-for-db            # regular init container: runs once, must exit 0
      image: busybox:1.36
      command: ["sh", "-c", "until nc -z postgres 5432; do sleep 2; done"]
    - name: log-shipper            # native sidecar: starts first, stops last
      image: fluent/fluent-bit:3.2
      restartPolicy: Always
      volumeMounts:
        - { name: logs, mountPath: /var/log/app }
  containers:
    - name: api
      image: ghcr.io/acme/api:sha-7f3c2a1
      volumeMounts:
        - { name: logs, mountPath: /var/log/app }
  volumes:
    - name: logs
      emptyDir: {}

Before native sidecars, people put the shipper in containers and hit two classic bugs: a Job never finished because the sidecar never exited, and the sidecar could die before the app during shutdown. If you read an older manifest with a sidecar in containers and a shell trick to kill it, that is why.

Running database migrations in an init container is common but has a catch: every replica runs them, at the same moment, on every rollout. Many teams run migrations as a separate Job (or a pipeline step) before the rollout instead.

Phases versus container states

kubectl get pods mixes two different things in its STATUS column, and knowing which is which speeds up debugging.

The pod phase is coarse: Pending (accepted, but not all containers are running yet, which includes waiting for a node and pulling images), Running, Succeeded, Failed, Unknown (the node stopped reporting). Each container has its own state: Waiting with a reason, Running, or Terminated with an exit code and reason.

CrashLoopBackOff, ImagePullBackOff and CreateContainerConfigError are not phases. They are the reason a container is Waiting. OOMKilled is the reason a container Terminated. After a crash the kubelet restarts the container with an exponential back-off (10 seconds, then 20, 40, up to a five-minute cap), which is why a crashing pod seems to sit there doing nothing.

Quick check
A pod shows 0/1 CrashLoopBackOff with RESTARTS 6. What is actually happening?
Need a nudge? A hint rules out a wrong answer.

Picking the right controller

You almost never create bare pods. A bare pod on a node that dies is simply gone. Controllers own pods and recreate them. Each controller encodes a different promise.

ControllerPromiseTypical workloads
DeploymentN interchangeable pods, rolling updatesHTTP APIs, web frontends, stateless workers
StatefulSetStable names (db-0, db-1), a volume per pod that follows it, ordered start and updateDatabases, Kafka, ZooKeeper, Elasticsearch
DaemonSetExactly one pod on every (matching) nodeLog collectors, node metrics agents, CNI and storage plugins
JobRun pods until a number of them succeedMigrations, backfills, one-off reports
CronJobCreate a Job on a scheduleNightly exports, cleanups, digests

A StatefulSet pod named db-1 keeps that name and its PersistentVolumeClaim across restarts and reschedules, and pods start in order (db-0 first). It needs a headless Service so each pod gets its own DNS name, which you will see in Kubernetes Networking. Running a database in a StatefulSet is entirely possible, but backups, failover and upgrades become your job. Most product teams use a managed database and keep the cluster stateless.

Jobs and CronJobs have the most production-relevant fields, and the defaults are rarely what you want:

k8s/nightly-report.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "0 2 * * *"
  timeZone: "Europe/London"        # without it, the controller's time zone is used
  concurrencyPolicy: Forbid         # default Allow: a slow run can overlap the next one
  startingDeadlineSeconds: 600      # skip a run that could not start within 10 minutes
  jobTemplate:
    spec:
      backoffLimit: 2               # default 6 retries
      activeDeadlineSeconds: 3600   # kill the whole Job after an hour
      ttlSecondsAfterFinished: 86400  # delete the finished Job and its pods after a day
      template:
        spec:
          restartPolicy: Never      # Jobs must use Never or OnFailure
          containers:
            - name: report
              image: ghcr.io/acme/reports:sha-7f3c2a1
              args: ["python", "-m", "reports.nightly"]

The "report ran twice" mystery from the opening is usually one of two things: concurrencyPolicy: Allow let a slow run overlap the next one, or a retry after a partial failure re-sent the emails. Kubernetes guarantees a Job runs at least once, not exactly once, so make job logic idempotent: record what you already processed and skip it on retry.

Match the pairs0/5 matched

Match each workload to the controller that fits it.

Choose an item, then its match on the other side.

How a Deployment really rolls out

A Deployment does not manage pods directly. It manages ReplicaSets, and each ReplicaSet manages pods. Every change to the pod template (image, env, resources, labels) creates a new ReplicaSet, named with a hash of the template, such as api-6d9f8c7b5. A rollout is the Deployment scaling the new ReplicaSet up and the old one down. Old ReplicaSets are kept at zero replicas; that history is what kubectl rollout undo scales back up.

A rollout is two ReplicaSets trading pods
Deployment api: replicas: 4Deployment apireplicas: 4ReplicaSet old: api-6d9f8c7b5ReplicaSet oldapi-6d9f8c7b5ReplicaSet new: api-58c4f9d7dReplicaSet newapi-58c4f9d7dv1 pods: 4 then 3, 2, 0v1 pods4 then 3, 2, 0v2 pods: 0 then 1, 2, 4v2 pods0 then 1, 2, 4Service api: app: apiService apiapp: apiscale downscale upready onlyready only

Before the change, one ReplicaSet owns all 4 v1 pods. Its name ends in a hash of the pod template.

1/5

The strategy fields decide the pace and the safety margin:

  • maxSurge (default 25%, rounded up): how many pods above replicas may exist during the rollout. More surge means a faster rollout and more spare capacity needed on the nodes.
  • maxUnavailable (default 25%, rounded down): how many pods below replicas you accept being not ready. Both cannot be zero.
  • minReadySeconds (default 0): a new pod must stay ready this long before it counts as available. Ten or twenty seconds catches the app that passes its first probe and then crashes.
  • progressDeadlineSeconds (default 600): if the rollout makes no progress for this long, the Deployment's Progressing condition flips to False with reason ProgressDeadlineExceeded, and kubectl rollout status exits non-zero. Kubernetes does not roll back for you. Your pipeline or GitOps tool must notice and act.
  • strategy.type: Recreate kills all old pods before starting new ones. Use it only when two versions must never run at once, such as a single-writer worker, and accept the downtime.

The rounding matters with small replica counts. Run the simulation and compare the default strategy with the "zero capacity loss" setting maxSurge: 100%, maxUnavailable: 0, and with a v2 that never becomes ready.

Pythonrollout_sim.py
import math def rollout(replicas, max_surge, max_unavailable, ready_after=2, max_ticks=8): surge = math.ceil(replicas * max_surge / 100) # rounds up unavailable = math.floor(replicas * max_unavailable / 100) # rounds down print(f"replicas={replicas} maxSurge={max_surge}%={surge} maxUnavailable={max_unavailable}%={unavailable}") old, new_ages = replicas, [] for tick in range(1, max_ticks + 1): new_ages = [age + 1 for age in new_ages] ready_new = sum(ready_after is not None and age >= ready_after for age in new_ages) # 1. scale up the new ReplicaSet: total pods may not exceed replicas + surge room = replicas + surge - (old + len(new_ages)) add = max(0, min(room, replicas - len(new_ages))) new_ages += [0] * add # 2. scale down the old ReplicaSet: ready pods may not drop below replicas - unavailable remove = max(0, min(old, old + ready_new - (replicas - unavailable))) old -= remove print(f" t{tick}: +{add} new -{remove} old | old={old} new={len(new_ages)} ready_new={ready_new} serving={old + ready_new}") if old == 0 and ready_new == replicas: print(" rollout complete") return print(" rollout stalled: Kubernetes keeps waiting (and later reports ProgressDeadlineExceeded)") rollout(4, 25, 25)rollout(4, 100, 0)rollout(4, 25, 25, ready_after=None)
Output
Press Run (⌘ Enter) to see what happens.

Three things to notice. With the defaults and 4 replicas, you serve on 3 pods for most of the rollout, so a service sized with no headroom will feel the deploy. With maxSurge: 100% and maxUnavailable: 0 you never drop below 4, but you briefly need room for 8 pods. And a broken v2 stalls with 3 old pods still serving: the rollout is safe, but you are running at reduced capacity until someone notices.

Predict the outputPython

What does this print?

import math
replicas = 3
max_surge = math.ceil(replicas * 0.25)
max_unavailable = math.floor(replicas * 0.25)
print(max_surge, max_unavailable)
Need a nudge? Hints walk you through it.

Namespaces, labels and contexts

Namespaces split one cluster into named areas, usually per team or per environment (payments, staging). Names only need to be unique within a namespace, and RBAC, resource quotas and network policies are usually set per namespace. Some objects are cluster-wide: nodes, PersistentVolumes, namespaces themselves.

Labels are the glue. A Deployment finds its pods by label, a Service finds its endpoints by label, and you filter with -l app=api,tier=web. Two rules save real pain. First, a Deployment's spec.selector is immutable after creation, so pick labels you can live with (app.kubernetes.io/name: api is the recommended convention). Second, the selector must match the template labels, or the API server rejects the object. Annotations are also key-value pairs, but they are not used for selection. Tools read them: a checksum of a config file, the git commit, a tool's settings.

Your kubeconfig file holds contexts: a cluster, a user and a default namespace. The worst kubectl mistake is a right command in the wrong context.

kubectl config get-contexts                       # list contexts, * marks the current onekubectl config use-context staging                # switch clusterkubectl config set-context --current --namespace=payments   # change default namespace

kubectx and kubens are small, popular tools that make those switches one word. Many engineers also show the current context in their shell prompt, and keep production in a separate kubeconfig they load on purpose.

The kubectl toolkit

These commands cover most of the day-to-day work. Learn the flags, not just the verbs.

kubectl get pods -o wide                     # node and pod IP for each podkubectl get deploy api -o yaml               # the live object, including statuskubectl describe pod api-58c4f9d7d-x2k4p     # read the Events section at the bottom firstkubectl events --for pod/api-58c4f9d7d-x2k4p # just the eventskubectl logs deploy/api -c api --since=10m   # one container's recent logskubectl logs api-58c4f9d7d-x2k4p --previous  # logs of the container that crashedkubectl exec -it deploy/api -- sh            # a shell inside a running containerkubectl port-forward deploy/api 8000:8000    # reach a pod from your laptopkubectl explain deployment.spec.strategy     # field docs from the cluster's own schemakubectl apply -f k8s/ --dry-run=server       # validate against the real API serverkubectl diff -f k8s/                         # what would change, before you applykubectl rollout history deploy/api           # revisions you can undo tokubectl top pods                             # live CPU and memory (needs metrics-server)

--dry-run=server is stronger than --dry-run=client: the API server runs validation and admission checks without saving, so it catches policy rejections and typos in field names. kubectl diff before every manual apply is a habit that prevents surprises in shared environments.

Debugging the common states

Every broken pod falls into a handful of shapes. Learn the first command for each.

What you seeUsual causeFirst move
PendingNo node has enough free CPU or memory for the requests, a node selector or taint excludes every node, or a PVC is not boundkubectl describe pod: the event says 0/5 nodes are available: 3 Insufficient memory...
ImagePullBackOff, ErrImagePullTag typo, missing pull secret for a private registry, or the image has no build for the node's CPU architecturedescribe pod shows the registry error; check the tag exists and the platform
CrashLoopBackOffThe process exits on start: missing env var, bad config, cannot reach a dependencykubectl logs <pod> --previous
OOMKilled (exit 137)The container exceeded its memory limitdescribe pod shows Last State: Terminated, Reason: OOMKilled; raise the limit or fix the leak
CreateContainerConfigErrorThe pod references a ConfigMap, Secret or key that does not existdescribe pod names the missing key
Running but 0/1 readyThe readiness probe failsdescribe pod shows probe failures; port-forward and hit the endpoint yourself

Exit code 137 is 128 + 9 (SIGKILL) and 143 is 128 + 15 (SIGTERM), the same as in Docker.

When the image is distroless and has no shell, kubectl exec fails. Use an ephemeral debug container instead: it joins the running pod with your tools, without restarting it.

kubectl debug -it api-58c4f9d7d-x2k4p --image=busybox:1.36 --target=api

--target puts the debug container in the app container's process namespace, so ps shows the app's processes.

Put it in order5 steps

A new deploy left pods in CrashLoopBackOff. Order a sensible investigation.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
A new pod stays Pending for ten minutes. describe shows 0/4 nodes are available: 4 Insufficient cpu. The nodes are only 30% busy according to kubectl top nodes. Why?
Need a nudge? A hint rules out a wrong answer.

Practice locally

You do not need a cloud account to get fluent. Any of these runs a real cluster on your laptop:

  • kind (Kubernetes in Docker): each node is a container. Fast to create and delete, and what many projects use in CI.
  • k3d: runs the lightweight k3s distribution in Docker. Very quick to start.
  • minikube: a single-node cluster with many add-ons (ingress, metrics-server).
  • Docker Desktop: has a built-in Kubernetes you can switch on in settings.
kind create cluster --name labkubectl apply -f k8s/kubectl get pods --watchkind delete cluster --name lab

A good exercise: deploy a Deployment, break it on purpose (wrong tag, missing Secret, memory limit of 32Mi, a readiness probe on the wrong port) and recognise each state from get and describe alone.

Key terms
ReplicaSet
Keeps a set number of pods matching one pod template. Deployments create a new one for every template change.
StatefulSet
A controller for pods that need stable names, per-pod volumes and ordered start-up, such as databases.
DaemonSet
A controller that runs one copy of a pod on every matching node.
native sidecar
An init container with restartPolicy: Always: it starts before the app, runs alongside it, and stops after it.
maxSurge / maxUnavailable
Rollout limits on how many extra pods may exist, and how many may be unavailable, during an update.
CrashLoopBackOff
A waiting reason: the container keeps exiting and the kubelet restarts it with a growing delay.
ephemeral container
A temporary debug container added to a running pod with kubectl debug.