How to Retrieve Logs from Crashed Kubernetes Pods Using kubectl --previous
When a pod crashes and continuously restarts, using kubelet logs may fail to capture output, but the kubectl --previous flag lets you access the logs of the previous container instance by reading the linked log files stored under /var/log/pods.
Scenario
When a pod is in a crash state and the container keeps restarting, using kubelet logs may never capture the logs.
Solution
Use the kubectl logs --previous command. The --previous flag prints the logs for the previous instance of the container in a pod, if it exists.
Single‑container pod: kubectl logs pod-name --previous Multi‑container pod:
kubectl logs pod-name --previous -c container-nameExample:
NAME READY STATUS RESTARTS AGE
nginx-7d8b49557c-c2lx9 2/2 Running 5
kubectl logs nginx-7d8b49557c-c2lx9 --previous
Error: xxxxxxxxxxxPrinciple
kubelet keeps the logs of the most recent failed containers. The logs are stored under /var/log/pods/podname as symbolic links to the Docker container log files. When --previous is used, kubelet reads the linked file of the last exited container.
Practice
List pods on a node:
ubuntu@~$ kubelet get pod
NAME READY STATUS RESTARTS AGE
busybox 1/1 Running 2394 99d
nginx-deployment-6wlhd 1/1 Running 0 79d
redis 1/1 Running 0 49dOn the node, view the log files stored by kubelet:
ls /var/log/pods/default_busybox_f72ab71a-5b3b-4ecf-940d-28a5c3b30683/busybox
2393.log 2394.logThe numbers indicate the restart count; 2393.log is the log after the 2393rd restart, and 2394.log after the 2394th.
These files are symbolic links to Docker’s JSON log files. Reading the current container’s logs uses the current file, while adding --previous reads the linked file of the previous container.
Manual verification by editing the linked files shows that kubectl logs reads the content of the linked files correctly.
Conclusion
kubelet reads log files from /var/log/pods/. The --previous flag also reads from this directory, using a dedicated symbolic link that points to the log file of the last exited container, allowing you to retrieve logs from a crashed pod.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
