Sign In

Curriculum 13: Debugging & Troubleshooting

Previous Container Logs

12 min · 25 XP

Viewing Previous Container Logs

When a container crashes and restarts, its current logs start fresh. The --previous flag retrieves logs from the last terminated container instance, which is critical for diagnosing CrashLoopBackOff errors.

The --previous Flag

# View logs from the previous container instance
kubectl logs my-pod --previous

# Short form
kubectl logs my-pod -p

# Previous logs for a specific container in a multi-container pod
kubectl logs my-pod -c my-container --previous

Debugging CrashLoopBackOff

When a pod enters CrashLoopBackOff, the container starts, crashes, and restarts in a loop with exponential backoff delays. The current container may have barely started, so its logs are empty or unhelpful. The previous logs capture what happened right before the crash:

# Check pod status first
kubectl get pod my-pod

# View the crash logs
kubectl logs my-pod --previous

# Combine with tail to see the last lines before crash
kubectl logs my-pod --previous --tail=50

Understanding Container Restarts

Check how many times a container has restarted:

kubectl get pod my-pod -o jsonpath='{.status.containerStatuses[0].restartCount}'

View the termination reason and exit code:

kubectl get pod my-pod -o jsonpath='{.status.containerStatuses[0].lastState}'

Common exit codes include: 137 (OOMKilled or SIGKILL), 1 (application error), and 143 (SIGTERM graceful shutdown).

Combining with Other Tools

# Get previous logs and search for errors
kubectl logs my-pod --previous | grep -i error

# Describe the pod for event-level context
kubectl describe pod my-pod

Only one previous instance is retained. Once the container restarts again, the earlier previous logs are lost. For persistent log storage, use a log aggregation system like Fluentd or Loki.