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.
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 onlocalhost:8000, and two containers in one pod cannot both listen on port 8000. - Shared volumes. Containers can mount the same volume. An
emptyDirvolume 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
initContainerswithrestartPolicy: 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.
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.
0/1 CrashLoopBackOff with RESTARTS 6. What is actually happening?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.
| Controller | Promise | Typical workloads |
|---|---|---|
| Deployment | N interchangeable pods, rolling updates | HTTP APIs, web frontends, stateless workers |
| StatefulSet | Stable names (db-0, db-1), a volume per pod that follows it, ordered start and update | Databases, Kafka, ZooKeeper, Elasticsearch |
| DaemonSet | Exactly one pod on every (matching) node | Log collectors, node metrics agents, CNI and storage plugins |
| Job | Run pods until a number of them succeed | Migrations, backfills, one-off reports |
| CronJob | Create a Job on a schedule | Nightly 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:
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 each workload to the controller that fits it.
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.
Before the change, one ReplicaSet owns all 4 v1 pods. Its name ends in a hash of the pod template.
The strategy fields decide the pace and the safety margin:
maxSurge(default25%, rounded up): how many pods abovereplicasmay exist during the rollout. More surge means a faster rollout and more spare capacity needed on the nodes.maxUnavailable(default25%, rounded down): how many pods belowreplicasyou 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'sProgressingcondition flips toFalsewith reasonProgressDeadlineExceeded, andkubectl rollout statusexits non-zero. Kubernetes does not roll back for you. Your pipeline or GitOps tool must notice and act.strategy.type: Recreatekills 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.
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.
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)
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 namespacekubectx 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 see | Usual cause | First move |
|---|---|---|
Pending | No node has enough free CPU or memory for the requests, a node selector or taint excludes every node, or a PVC is not bound | kubectl describe pod: the event says 0/5 nodes are available: 3 Insufficient memory... |
ImagePullBackOff, ErrImagePull | Tag typo, missing pull secret for a private registry, or the image has no build for the node's CPU architecture | describe pod shows the registry error; check the tag exists and the platform |
CrashLoopBackOff | The process exits on start: missing env var, bad config, cannot reach a dependency | kubectl logs <pod> --previous |
OOMKilled (exit 137) | The container exceeded its memory limit | describe pod shows Last State: Terminated, Reason: OOMKilled; raise the limit or fix the leak |
CreateContainerConfigError | The pod references a ConfigMap, Secret or key that does not exist | describe pod names the missing key |
Running but 0/1 ready | The readiness probe fails | describe 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.
A new deploy left pods in CrashLoopBackOff. Order a sensible investigation.
- Tap the steps below in the right order.
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?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 labA 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.
- 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.