Sub topic 2
Container States: Waiting, Running, Terminated
This chapter assumes you know what pods, containers, and namespaces are, and that you can run kubectl get and kubectl describe. It builds on the previous chapter, where you saw that a pod phase is only a coarse summary.
Where the status text comes from
A pod phase such as Pending or Running describes the whole pod. Each container inside the pod has its own state, and the kubelet (the agent on each node) reports it in status.containerStatuses. Status text like ImagePullBackOff or CrashLoopBackOff is not a phase. It is the reason field of a container state, and kubectl get pods copies it into the STATUS column.
A container is always in exactly one of three states.
| State | Meaning | Common reasons |
|---|---|---|
| Waiting | The container is not running yet and is waiting on something. | `ContainerCreating`, `ErrImagePull`, `ImagePullBackOff`, `CrashLoopBackOff` |
| Running | The process started and has not exited. | none |
| Terminated | The process ran and exited, or could not start. | `Completed`, `Error`, `OOMKilled` |
Reading the state
kubectl describe pod web prints a State: block for each container. For a container that is restarting, you will also see Last State:, which holds the previous instance.
kubectl describe pod web | grep -A 8 'State:'Typical output for a crashing container looks like this:
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Error
Exit Code: 1
Restart Count: 5The current state says what the container is doing now. The last state says why the previous run ended. For a crash loop, the answer you need is usually in Last State, not State.
Pulling the fields with jsonpath
To read the same data in a script, query the container status directly.
kubectl get pod web -o jsonpath='{.status.containerStatuses[0].state}'
kubectl get pod web -o jsonpath='{.status.containerStatuses[0].lastState}'Common mistakes
- Treating
Runningin the pod STATUS column as healthy. A pod can be in phaseRunningwhile one container is inWaitingwithCrashLoopBackOff. - Reading only
Stateand ignoringLast StateandRestart Count. - Forgetting that init containers have their own states. A pod stuck at
Init:0/1has an init container that has not finished.
Exercise
A pod shows STATUS CrashLoopBackOff. Which container state is it in right now, and where do you look to find out why the previous run ended?
Show answer
The container is in the Waiting state, with CrashLoopBackOff as the reason. The cause of the last failure is in the Last State block (Terminated), which shows the exit code and reason. You can see it in kubectl describe pod or in .status.containerStatuses[].lastState.