Sub topic 13
Reading logs from the crashed instance
This chapter assumes you can run kubectl get and kubectl describe, and that you know a pod can hold several containers. It also assumes you know a container is restarted in place when it exits. You should already know what CrashLoopBackOff means.
Why plain `kubectl logs` often shows nothing useful
When a container crashes, the kubelet (the node agent that runs containers) starts a new instance in the same pod. kubectl logs web reads the log of the current instance. If that instance has just started, its log is empty or holds only startup lines. The error that killed the previous instance is in a different log.
The --previous flag asks for the log of the last terminated instance of the container.
kubectl logs web --previousKubernetes keeps only the most recent terminated instance. After the next restart, the one before it is gone from kubectl logs.
Finding out how it ended
The log shows what the app said. The container's terminated state shows how the container ended. Read it with a JSONPath query:
kubectl logs web --previous
kubectl get pod web -o jsonpath='{.status.containerStatuses[0].lastState.terminated}'The second command prints the exit code, the reason, and the start and finish times. If the start and finish times are only a second or two apart, the app fails during startup. That points to a bad config, a missing environment variable, or an unreachable dependency. A longer run time points to a failure while serving traffic.
Common errors
previous terminated container "app" in pod "web" not found. The container has not crashed yet, so there is no previous instance. Checkkubectl get pod webfor the restart count.- Wrong container. In a multi-container pod, add
-c <name>. Without it, kubectl picks a default container or asks you to choose, and you may read a healthy sidecar's log. - Index mismatch.
containerStatuses[0]is the first container in the status list. For other containers, check the name withkubectl get pod web -o jsonpath='{.status.containerStatuses[*].name}'. - Empty previous log. The process may have been killed before it wrote anything. Check the exit code and reason in the terminated state.
When the log is not enough
Some containers exit before they write a single line. In that case, use the terminated-state data from this chapter and move on to exit codes and kubectl debug, which later chapters cover.
Exercise
A pod named api shows CrashLoopBackOff. You run kubectl logs api and see only one startup line. Which two commands should you run next, and what does each tell you?
Show answer
Run kubectl logs api --previous to read the output of the instance that crashed, which should contain the error. Then run kubectl get pod api -o jsonpath='{.status.containerStatuses[0].lastState.terminated}' to see the exit code, reason, and start and finish times, which tell you how and how quickly the container ended.