kubectl logs --previous: Usage, Options & Common CI Errors
Read the log of the container instance that already crashed.
kubectl logs --previous prints the log of a container's prior, terminated instance rather than the running one. It is the single most useful command for diagnosing CrashLoopBackOff, where the container dies before you can attach to the live one.
What it does
kubectl logs POD --previous (or -p) reads the log of the last terminated instance of the container - the one that crashed and was restarted. -c selects the container in a multi-container pod. It works only while the prior instance's log is still retained on the node.
Common usage
kubectl logs my-pod --previous
kubectl logs my-pod -p -c app
kubectl logs my-pod -p --tail=200
kubectl describe pod my-pod | grep -A3 'Last State' # restart reasonCommon errors in CI
"previous terminated container \"X\" in pod \"Y\" not found" means there is no prior instance (the container has not restarted, so use the current log) or the node already rotated the previous log away (common after several restarts or once a fresh node replaces the pod). In CI, capture --previous immediately on failure rather than after retries, since each retry can push the crashing instance's log out of retention. Pair it with kubectl describe to read the Last State exit code, which tells you whether it was an OOMKill, a non-zero exit, or a SIGTERM.
Using this in CI
A runner has no kubeconfig, no cached context, and no interactive auth. Every kubectl invocation in CI needs the context supplied explicitly, and most confusing CI failures here are the command running against the wrong cluster or no cluster at all.
# never rely on the ambient context on a runner
kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get pods
# confirm what you are actually connected to before mutating anything
kubectl config current-context
kubectl cluster-info
# fail fast instead of hanging on an unreachable API server
kubectl --request-timeout=30s get nodes