kubectl logs: Viewing Container Logs
What you'll learn: How to retrieve and monitor container logs using kubectl logs to troubleshoot and understand application behavior in Kubernetes.
Why Container Logs Matter
Just as a ship's captain reviews the logbook to understand what happened during a voyage, you need to view container logs to see what your applications are doing inside pods. The kubectl logs command is your window into the standard output and error streams of your containers.
Basic Log Retrieval
To view logs from a single-container pod:
kubectl logs <pod-name>
For multi-container pods, you must specify which container:
kubectl logs <pod-name> -c <container-name>
Following Logs in Real-Time
Use the -f or --follow flag to stream logs continuously, similar to tail -f:
kubectl logs -f <pod-name>
This is invaluable when watching application startup or monitoring live traffic.
Adding Timestamps
Include timestamps to understand when events occurred:
kubectl logs <pod-name> --timestamps
Viewing Recent Logs
Limit output to the last N lines:
kubectl logs <pod-name> --tail=50
Or retrieve logs from a specific time window:
kubectl logs <pod-name> --since=1h
Handling Previous Container Instances
If a container crashed and restarted, view logs from the previous instance:
kubectl logs <pod-name> --previous
This is critical for diagnosing why a container failed.
Multi-Container Best Practices
In multi-container pods, always specify the container name explicitly to avoid confusion. You can list all containers in a pod first using kubectl describe pod.
Key Takeaway: kubectl logs is your primary tool for viewing container output in Kubernetes, with options for following live streams, filtering by time, viewing previous instances, and handling multi-container pods through the -c flag.