Pods and workloadsLesson 2 of 7
Pod lifecycle, restarts and termination
Read a pod's phase, container states and conditions, predict crash-loop back-off, decode exit codes, and shut a container down without dropping requests.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
Reconcile, in 8 scenes
Phases
Every pod has a phaseA one-word summary in status.phase of where a pod is in its life: Pending, Running, Succeeded, Failed or Unknown., and there are only five:
| Phase | Meaning |
|---|---|
Pending | Accepted by the API server, but at least one container is not yet set up: the pod is waiting to be scheduled, pulling images, or running init containers. |
Running | Bound to a node with all containers created. At least one container is running, starting or restarting. |
Succeeded | Every container exited 0 and none will be restarted. |
Failed | Every container has terminated, at least one in failure, and none will be restarted. |
Unknown | The pod’s state cannot be obtained, usually because the node stopped reporting. |
The phase is deliberately coarse, and it hides most problems. A container that crashes every few seconds leaves its pod Running, because the kubelet keeps restarting it. A pod whose image cannot be pulled stays Pending. Failed and Succeeded are terminal: nothing restarts a pod that reaches them, so under restartPolicy: Always a pod almost never gets there. It does when the kubelet evicts it for node pressure (phase Failed, reason Evicted), and for that the kubelet ranks pods by whether their usage exceeds their requests, then by priority, then by usage relative to requests, not by QoS class. QoS class sets the kernel’s oom_score_adj instead (1000 for BestEffort), which matters when the kernel’s OOM killer acts before the kubelet does.
The STATUS column of kubectl get pods is not the phase. kubectl computes it from the phase, the container states and the deletion timestamp, which is why it can print CrashLoopBackOff, ContainerCreating or Terminating. None of those is a phase: the first two are container reasons, and Terminating means metadata.deletionTimestamp is set.
Container states and reasons
Each container has a state of its own in status.containerStatuses: Waiting, Running or Terminated. Waiting and Terminated carry a reason, and the reason is where the diagnosis starts.
| State | Reason | What it means |
|---|---|---|
| Waiting | ContainerCreating | The kubelet is still setting up: the pod sandbox, its network, its volumes, or a slow image pull. |
| Waiting | PodInitializing | Init containers have not finished. |
| Waiting | ErrImagePull, ImagePullBackOff | The pull failed, and the kubelet retries with a back-off of 10s doubling to 300s. |
| Waiting | CreateContainerConfigError | The spec refers to something missing, such as a Secret key used in env. |
| Waiting | CrashLoopBackOff | The container exited and the kubelet is waiting out the restart back-off. |
| Running | The process is up. Readiness is tracked separately. | |
| Terminated | Completed | The process exited 0. |
| Terminated | Error | The process exited non-zero or was killed by a signal. |
| Terminated | OOMKilled | The kernel killed it for exceeding its memory limit. |
Next to state, each container status has lastState, which records how the previous run ended. When a container is in CrashLoopBackOff, state says only that it is waiting; lastState.terminated holds the exit code, reason and timestamps that explain why.
A pod stuck in ContainerCreating for minutes has usually not got past the sandbox: the CNI plugin could not assign an IP, or a volume could not be mounted. Its events name the step. Image problems show their own reasons.
Conditions
Conditions are the pod’s checklist, in status.conditions. Each has a type, a status of True, False or Unknown, and a reason, message and lastTransitionTime that tell you when and why it last changed:
PodScheduled: the scheduler bound the pod to a node.PodReadyToStartContainers, stable in Kubernetes 1.37: the sandbox exists, networking is configured and volumes are mounted.Initialized: every init container completed and every native sidecar started.ContainersReady: every container is ready.Ready: the pod can serve, and matching Services should send it traffic.DisruptionTarget: the pod is about to be removed by preemption, eviction or garbage collection.PodResizePendingandPodResizeInProgress: an in-place resize is waiting or under way.
Ready is the condition other components act on. The EndpointSlice controller marks a pod’s endpoint ready only while the pod is Ready, and a Deployment counts it available only after that. A container with no readiness probe is ready as soon as it is running. With a readiness probe, it is ready only while the probe passes, using one of four mechanisms: exec, httpGet, tcpSocket, or grpc (GA since 1.27). The docs suggest that a readiness probe may check strict back-end dependencies; weigh that against what happens when a database shared by every replica goes down, which is that every replica turns unready at once and the Service has nowhere to send anything.
kubectl wait --for=condition=Ready pod/api blocks until the condition holds, which is the right way to sequence a script.
restartPolicy and backoff
restartPolicy decides what the kubelet does when a container exits. Always, the default for every pod, restarts it whatever the exit code. OnFailure restarts it only after a non-zero exit. Never leaves it stopped. Deployments, StatefulSets and DaemonSets accept only Always; Jobs use OnFailure or Never.
A restart happens in place: same pod, same node, same IP, same volumes, so an emptyDir keeps its files across container restarts. It is not free. The kubelet delays restarts with an exponential back-offThe delay the kubelet adds before restarting a container that keeps exiting, doubling each time up to a cap.: the first restart comes at once, then the kubelet waits 10s, 20s, 40s, 80s, 160s and then 300s for every restart after that. Once a container has run for 10 minutes without a problem, the timer resets. While it waits, the container is Waiting with reason CrashLoopBackOff. The pod crasher below runs a busybox shell that prints two lines and exits 1:
kubectl get pod crasher
NAME READY STATUS RESTARTS AGE crasher 0/1 CrashLoopBackOff 1 (1s ago) 5s
sleep 30
kubectl get pod crasher
NAME READY STATUS RESTARTS AGE crasher 0/1 CrashLoopBackOff 3 (1s ago) 35s
sleep 60
kubectl get pod crasher
NAME READY STATUS RESTARTS AGE crasher 0/1 CrashLoopBackOff 4 (21s ago) 95s
kubectl get pod crasher -o jsonpath='{.status.phase}'
Running
kubectl logs crasher --previous
loading config config missing
Three restarts in the first 35 seconds, then one in the next minute. A container that has been crashing for a while restarts every five minutes, so after a fix to its dependencies, deleting the pod (or rolling its Deployment) is faster than waiting for the next attempt.
Two node-level settings change the schedule. With KubeletCrashLoopBackOffMax, beta and on by default since Kubernetes 1.35, a node can lower the cap through crashLoopBackOff.maxContainerRestartPeriod in its kubelet configuration, anywhere from 1s to 300s. ReduceDefaultCrashLoopBackOffDecay, alpha since 1.33, changes the defaults to a 1s start and a 60s cap, and only where it is enabled. On a default node the numbers above hold.
Exit codes
The exit code in lastState.terminated tells you what ended the process. Codes above 128 mean a signal did: the code is 128 plus the signal number.
| Exit code | Typical reason | What happened |
|---|---|---|
| 0 | Completed | The process finished successfully. |
| 1 (or another small number) | Error | The application decided to exit: bad configuration, a missing variable, an unhandled exception. Read its logs. |
| 137 | OOMKilled or Error | SIGKILL (9). With OOMKilled, the kernel killed it for exceeding its memory limit. With Error, something else did, usually the kubelet when a grace period ran out. |
| 143 | Error | SIGTERM (15). The kubelet asked the process to stop (a delete or a failed liveness probe) and it died of the signal. |
The pod cache runs an image whose memory grows steadily, under a 128Mi limit:
kubectl wait --for=jsonpath='{.status.containerStatuses[0].restartCount}'=1 pod/cache --timeout=60s
pod/cache condition met
kubectl get pod cache
NAME READY STATUS RESTARTS AGE cache 1/1 Running 1 (1s ago) 17s
kubectl get pod cache -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason} {.status.containerStatuses[0].lastState.terminated.exitCode}'
OOMKilled 137
Between restarts the pod looks healthy: Running, 1/1. The restart count and lastState are what give it away. The memory limit is enforced by the OOM killer every time; the fix is a limit that fits the workload’s real footprint, or a smaller footprint. On a cgroup v2 node, in-place resize (GA in Kubernetes 1.35) can raise the limit of a running pod without recreating it.
The cluster also runs a Deployment, web, whose containers have a 128Mi limit. The first button deletes one of its pods, and the ReplicaSet creates a new pod with a new name; the second fills a web container’s memory until the kernel kills it, and the same pod restarts it with OOMKilled and 137 in lastState.
End a web container
- Runs kubectl delete pod <pod>. Its ReplicaSet notices one replica missing and makes a new pod.
- Runs kubectl exec <pod> -- sh -c 'tail /dev/zero'. The container passes its memory limit, the kernel kills it, and the kubelet restarts it.
Each button runs its command on the cluster. This line follows what happens next.
The termination sequence
When you delete a pod, the API server does not remove it. It sets deletionTimestamp and a grace period (the pod’s terminationGracePeriodSeconds, 30 by default, unless kubectl delete --grace-period overrides it), and from then on kubectl shows the pod as Terminating. Two things then happen at the same time.
On the node, the kubelet runs each container’s preStop hook, if it has one. When the hook returns, the container runtime sends SIGTERM (or the image’s STOPSIGNAL) to PID 1 in each container. If anything is still running when the grace period expires, it gets SIGKILL, and the kubelet removes the pod from the API. The grace period is measured from the start, so the hook and the shutdown share it.
In the control plane, the EndpointSlice controller marks the pod’s endpoints terminating: true and ready: false. kube-proxy stops sending new connections to them, and so do ingress controllers, Gateway implementations and cloud load balancers, each as soon as it observes the change. Many troubleshooting guides use the community ingress-nginx controller as their example. Kubernetes SIG Network and the Security Response Committee announced its retirement in November 2025 and retired it on March 24, 2026, so it receives no further releases or security fixes; use a Gateway API implementation or another maintained controller.
kubectl get endpoints api
Warning: v1 Endpoints is deprecated in v1.33+; use discovery.k8s.io/v1 EndpointSlice NAME ENDPOINTS AGE api 10.244.1.3:8080 5s
kubectl get endpointslices -l kubernetes.io/service-name=api -o jsonpath='{.items[0].endpoints[0].conditions}'
{"ready":true,"serving":true,"terminating":false}kubectl delete pod api --wait=false
pod "api" deleted from default namespace
kubectl get pod api
NAME READY STATUS RESTARTS AGE api 1/1 Terminating 0 5s
kubectl get endpointslices -l kubernetes.io/service-name=api -o jsonpath='{.items[0].endpoints[0].conditions}'
{"ready":false,"serving":true,"terminating":true}The first command prints a warning because the v1 Endpoints API is deprecated since Kubernetes 1.33. EndpointSlices are where Service backends live, and serving: true on a terminating endpoint tells a load balancer that can drain connections that the pod still answers.
The two halves are not synchronised. If the process exits the moment it receives SIGTERM, requests that are already on their way from a proxy that has not caught up yet arrive at a closed port. That gap is what a preStop hook covers.
Signals need a process that listens. PID 1 in a container gets no default signal handling from the kernel, so a process that installs no SIGTERM handler simply ignores it. A shell script as PID 1 is the classic case:
kubectl delete pod sleeper --wait=false
pod "sleeper" deleted from default namespace
kubectl get pod sleeper
NAME READY STATUS RESTARTS AGE sleeper 1/1 Terminating 0 5s
kubectl wait --for=delete pod/sleeper --timeout=60s
pod/sleeper condition met
kubectl get pod sleeper
Error from server (NotFound): pods "sleeper" not found
The pod runs sh -c "sleep 3600". kubectl wait --for=delete returns only when the object is gone: it stayed Terminating for the full 30 seconds and then died of SIGKILL, with exit code 137. Use the exec form of command, end wrapper scripts with exec your-app, or run a small init such as tini so SIGTERM reaches a process that handles it.
In a pod with native sidecars (init containers with restartPolicy: Always, GA since Kubernetes 1.33), the kubelet waits until every main container has stopped before it sends SIGTERM to the sidecars, and stops them in reverse order. A slow main container eats into the sidecars’ share of the grace period.
preStop hooks
A preStop hook runs inside the termination sequence, before SIGTERM, and has three handler types:
execruns a command inside the container, counted against its resources. Use it to ask the server to drain, such asnginx -s quit.httpGethas the kubelet send a request to the container, for an app that exposes a shutdown endpoint.sleep, GA in Kubernetes 1.34, pauses for a number of seconds without needing a shell or asleepbinary in the image. It is the simplest way to keep serving while load balancers catch up. A value of 0, also GA in 1.34, makes it a no-op.
apiVersion: v1
kind: Pod
metadata:
name: api
labels:
app: api
spec:
terminationGracePeriodSeconds: 45
containers:
- name: api
image: ghcr.io/kx-labs/web:1.1
ports:
- name: http
containerPort: 8080
lifecycle:
preStop:
sleep:
seconds: 10
This pod keeps answering for 10 seconds after deletion while proxies remove it, then gets SIGTERM with 35 seconds left to finish in-flight work. Budget the grace period as hook time plus shutdown time plus a margin. If the hook is still running when the grace period ends, the kubelet grants a one-off 2-second extension and then kills the container. A hook that fails also kills the container and records a FailedPreStopHook event. Hooks are delivered at least once, so make them safe to run twice.
Logs across restarts
kubectl logs reads the current instance of a container. After a restart, the instance that crashed is the interesting one, and kubectl logs api --previous reads it. The kubelet keeps only the current and the previous instance, and it discards both when the pod is deleted; anything older belongs in a log pipeline that ships output off the node.
A few flags save time: -c picks a container, --all-containers reads them all, -l app=api --prefix reads every matching pod and labels each line, and kubectl logs deploy/api picks one pod of a Deployment for you.
When there is nothing to read
Some failures leave no log line. The process may exit before it writes anything, or the image may be distroless with no shell to exec into. kubectl debug adds an ephemeral containerA temporary container added to a running pod for debugging. It cannot be removed and is never restarted. to the running pod. Pass --target=<container> so it joins that container’s process namespace; without it, ps in the debug container shows only its own processes. In kubectl 1.36 and later the default --profile is general (earlier releases defaulted to legacy, which 1.36 removed); baseline, restricted, netadmin and sysadmin are the others.
kubectl debug node/kx-worker -it --image=busybox:1.37 starts a pod on the node that shares the node’s IPC, network and process namespaces and mounts the node’s root filesystem at /host. It is not privileged; add --profile=sysadmin when you need that.
Not every problem ends a container. A container that stays Running but answers slowly may be CPU-throttled, and throttling happens only when it reaches its CPU limit, not when it exceeds its request. kubectl top reports usage from the metrics API and never shows throttling. Compare container_cpu_cfs_throttled_periods_total with container_cpu_cfs_periods_total from the kubelet’s cAdvisor metrics to see it.
kubectl --context kind-kx run looper --image=busybox:1.37 -- sh -c 'echo starting; exit 1'kubectl --context kind-kx get pod looper -wkubectl --context kind-kx wait --for=jsonpath='{.status.containerStatuses[0].restartCount}'=1 pod/looper --timeout=60skubectl --context kind-kx logs looper --previouskubectl --context kind-kx get pod looper -o jsonpath='{.status.phase} {.status.containerStatuses[0].lastState.terminated.exitCode}'kubectl --context kind-kx run stubborn --image=busybox:1.37 -- sh -c 'sleep 3600'kubectl --context kind-kx delete pod stubbornkubectl --context kind-kx delete pod looper
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Press Ctrl+C to stop the watch once the restart count passes 1. Deleting stubborn takes the full 30-second grace period, because sh as PID 1 ignores SIGTERM.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Distinguish pod phase, container state and pod conditions in kubectl output. (not yet met)
- Predict CrashLoopBackOff timing, with a delay that doubles from 10s to a 300s cap and resets after 10 minutes of clean running. (not yet met)
- Read exit codes 0, 1, 137 and 143 and say what ended the container. (not yet met)
- Design graceful shutdown with a preStop hook, SIGTERM handling and terminationGracePeriodSeconds. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 19 corrections
The notes saidUnlike sidecar containers that run alongside the application, init containers complete and exit
CorrectedNative sidecars are initContainers with restartPolicy: Always and keep running alongside the app. They have been stable since v1.33.
Sourcekubernetes.io/docs/concepts/workloads/pods/sidecar-containers
The notes saidMemory limits are enforced strictly
CorrectedMemory limits are still enforced by OOM kill. In-place Pod resize (GA in v1.35, needs cgroup v2) lets you change requests and limits without restarting the Pod.
Sourcekubernetes.io/blog/2025/12/19/kubernetes-v1-35-in-place-pod-resize-ga
The notes saidProbe mechanisms: HTTP, TCP, exec
CorrectedgRPC probes are a fourth mechanism, GA since v1.27.
The notes saidPod conditions: PodScheduled, Initialized, ContainersReady, Ready
CorrectedCurrent releases add PodReadyToStartContainers (stable since v1.37), DisruptionTarget, PodResizePending and PodResizeInProgress.
Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
The notes saidAlways is the default restartPolicy for pods created by controllers
CorrectedAlways is the default restartPolicy for every Pod. Workload controllers such as Deployments accept only Always.
Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
The notes saidPods that fail might be restarted depending on restart policy
CorrectedFailed is a terminal phase. Under Always or OnFailure the kubelet restarts the container in place with exponential backoff (CrashLoopBackOff), and the Pod stays Running.
Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
The notes saidPods stuck in ContainerCreating usually mean image pull issues
CorrectedA failed pull shows as ErrImagePull or ImagePullBackOff; a slow pull of a large image does show ContainerCreating. A Pod stuck in ContainerCreating usually means the sandbox, networking (CNI/IP) or volume mounts failed, which are the prerequisites for PodReadyToStartContainers.
Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
The notes saidReadiness probes should check shared dependencies such as the database
CorrectedKubernetes docs do suggest readiness checks for strict back-end dependencies. The risk, which those docs don't state, is that one shared-dependency failure marks every replica unready at once and empties the Service.
The notes saidBestEffort pods are the first to be evicted
CorrectedThe kubelet doesn't use QoS class to order evictions. It ranks Pods by whether usage exceeds requests, then by priority, then by usage relative to requests. QoS class sets the OOM-killer adjustment (oom_score_adj 1000 for BestEffort).
Sourcekubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction
The notes saidkubectl get endpoints my-service
Correctedcore/v1 Endpoints is deprecated as of Kubernetes 1.33, and kubectl prints 'v1 Endpoints is deprecated in v1.33+; use discovery.k8s.io/v1 EndpointSlice'. Use kubectl get endpointslices -l kubernetes.io/service-name=my-service.
The notes saidkubectl get pods -n ingress-nginx / ingress-nginx controller as the example
CorrectedKubernetes SIG Network announced the retirement of ingress-nginx on Nov 11, 2025. Maintenance ended in March 2026, and the project gets no further releases or security fixes. Use a Gateway API implementation or another maintained controller (on EKS, the AWS Load Balancer Controller).
The notes saidDocker Hub rate limits pulls
CorrectedTrue. Docker documents the limits per 6-hour window, not hourly: 100 pulls for unauthenticated users per IPv4 address or IPv6 /64, 200 for authenticated Personal accounts, and unlimited for Pro, Team and Business. Authenticate pulls or mirror images (e.g. through an ECR pull-through cache).
The notes saidCrashLoopBackOff backoff behavior
CorrectedThe default backoff starts at 10s and doubles (20s, 40s, …) up to 300s, and resets once a container runs for 10 minutes without problems. KubeletCrashLoopBackOffMax (alpha 1.32, beta and on by default from 1.35) lets a node lower the cap through the kubelet's maxContainerRestartPeriod. ReduceDefaultCrashLoopBackOffDecay (alpha since 1.33) shortens the defaults only when enabled.
Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
The notes saidkubectl debug behavior
Correctedkubectl debug --profile accepts legacy, general, baseline, restricted, netadmin and sysadmin. kubectl 1.36 made general the default profile (previously legacy); the kubernetes.io task pages may still describe legacy.
The notes said'kubectl debug node/… creates a privileged pod'
CorrectedConfirmed. The node debugging pod shares the node's IPC, network and PID namespaces and mounts the node's root filesystem at /host, but it isn't privileged. Use --profile=sysadmin for a privileged container.
Sourcekubernetes.io/docs/tasks/debug/debug-cluster/kubectl-node-debug
The notes said'Pods using more than requests might be throttled (CPU)'
CorrectedConfirmed. CFS throttling happens only when a container reaches its CPU limit. Above its request, a container competes for spare CPU in proportion to its request (CPU weight); a container with no CPU limit isn't throttled by CFS quota.
Sourcekubernetes.io/docs/concepts/configuration/manage-resources-containers
The notes saidThe metrics.k8s.io API (kubectl get --raw …/pods/my-pod) and kubectl top show usage only, not throttling
CorrectedConfirmed. metrics.k8s.io (and kubectl top) reports only CPU and memory usage for autoscaling. To see throttling, use cAdvisor's container_cpu_cfs_throttled_periods_total relative to container_cpu_cfs_periods_total (kubelet /metrics/cadvisor, Prometheus or Container Insights).
Sourcekubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline
The notes said'kubectl debug my-pod --image=busybox' without --target=<container> can't see the app's processes
CorrectedConfirmed. An ephemeral container joins the target container's process namespace only when you pass --target=<container> (and the runtime supports it); otherwise ps shows only the debug container's processes.
Sourcekubernetes.io/docs/tasks/debug/debug-application/debug-running-pod
The notes said'Terminating' is a kubectl display state, not a pod phase
CorrectedConfirmed. Pod phase is only Pending, Running, Succeeded, Failed or Unknown. kubectl shows 'Terminating' when deletionTimestamp is set; ContainerCreating, ErrImagePull and CrashLoopBackOff are container state reasons, and the phase stays Pending during image pulls.
Sourcekubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle
- kubernetes.io/docs/concepts/workloads/pods/pod-termination
- kubernetes.io/docs/concepts/containers/container-lifecycle-hooks
- kubernetes.io/docs/concepts/workloads/pods/sidecar-containers
- kubernetes.io/docs/concepts/workloads/pods/probes
- kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction
- kubernetes.io/docs/concepts/configuration/manage-resources-containers
- kubernetes.io/blog/2025/12/19/kubernetes-v1-35-in-place-pod-resize-ga
- kubernetes.io/docs/concepts/services-networking/endpoint-slices
- kubernetes.io/blog/2025/04/24/endpoints-deprecation
- kubernetes.io/blog/2025/11/11/ingress-nginx-retirement
- kubernetes.io/blog/2026/01/29/ingress-nginx-statement
- docs.docker.com/docker-hub/usage/pulls
- kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod
- kubernetes.io/docs/tasks/debug/debug-cluster/kubectl-node-debug
- kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline
Pod lifecycle, restarts and termination
↓ ↑ step, 1 to 8 scene, Esc leave