Retrieving Previous Container Logs in Kubernetes with kubectl --previous
When a pod crashes and continuously restarts, using the standard kubelet logs may fail to capture output, but the kubectl --previous flag can retrieve logs from the prior container instance by accessing the kubelet‑managed log files under /var/log/pods.
Scenario : If a pod is in a crash loop and the container keeps restarting, the usual kubelet logs command may not capture any output.
Solution : Use the kubectl logs --previous option, which prints logs from the previous instance of the container if it exists.
For a single‑container pod:
kubectl logs pod-name --previousFor a multi‑container pod:
kubectl logs pod-name --previous -c container-namePrinciple : kubelet keeps log files for the most recent failed containers in /var/log/pods/ . It creates symbolic links to the Docker container log files, and an additional link points to the previous container’s log, which the --previous flag reads.
Practice : Listing pods, inspecting the log directory, and viewing the linked log files demonstrates that --previous reads the older log file while the default command reads the current one.
ls /var/log/pods/default_busybox_f72ab71a-5b3b-4ecf-940d-28a5c3b30683/busybox
2393.log 2394.logThese files are symbolic links to the Docker container logs; the numeric suffix indicates the restart count (e.g., 2393 for the 2393rd restart).
By editing the linked files or creating regular files in place of the links, you can verify that kubectl logs reads the current file, while kubectl logs --previous reads the file linked to the previous container.
Conclusion : kubelet reads log files from /var/log/pods/ , and the --previous flag accesses the log file of the last terminated container via a dedicated symbolic link, allowing retrieval of crash‑loop logs.
Cloud Native Technology Community
The Cloud Native Technology Community, part of the CNBPA Cloud Native Technology Practice Alliance, focuses on evangelizing cutting‑edge cloud‑native technologies and practical implementations. It shares in‑depth content, case studies, and event/meetup information on containers, Kubernetes, DevOps, Service Mesh, and other cloud‑native tech, along with updates from the CNBPA alliance.
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.