kubectl logs -- Reading Container Output
Application logs are your first stop when something goes wrong. kubectl logs streams the standard output and standard error from containers running in your Pods.
Basic Usage
# View logs from a pod
kubectl logs my-app-7d4b8c6f5-abc12
# View logs from a specific deployment's pods
kubectl logs deployment/my-app
Following Logs in Real Time
The -f flag streams logs as they are written, similar to tail -f:
kubectl logs my-app-7d4b8c6f5-abc12 -f
Press Ctrl+C to stop streaming.
Previous Container Logs
When a container crashes and restarts, the current logs show only the new instance. Use --previous to see logs from the last instance:
kubectl logs my-app-7d4b8c6f5-abc12 --previous
This is essential for debugging CrashLoopBackOff errors, where the container keeps crashing before you can read its output.
Multi-Container Pods
If a Pod has multiple containers, you must specify which container's logs you want:
# List containers in a pod
kubectl get pod my-app -o jsonpath='{.spec.containers[*].name}'
# View logs from a specific container
kubectl logs my-app -c sidecar
# View logs from all containers
kubectl logs my-app --all-containers
Time-Based Filtering
Limit logs to a specific time window:
# Logs from the last hour
kubectl logs my-app --since=1h
# Logs from the last 30 minutes
kubectl logs my-app --since=30m
# Logs since a specific time
kubectl logs my-app --since-time='2025-01-15T10:00:00Z'
Tail and Line Limits
Control how much output you see:
# Show only the last 100 lines
kubectl logs my-app --tail=100
# Combine with follow to see the last 20 lines then stream
kubectl logs my-app --tail=20 -f
Logs by Label
View logs from all Pods matching a label selector:
# All pods with app=nginx
kubectl logs -l app=nginx
# All containers in all matching pods
kubectl logs -l app=nginx --all-containers
# Follow logs from all matching pods
kubectl logs -l app=nginx -f
Practical Troubleshooting Pattern
When a Pod is in CrashLoopBackOff:
# Step 1: Check the current logs
kubectl logs my-app
# Step 2: If empty, check previous container logs
kubectl logs my-app --previous
# Step 3: If the pod has multiple containers, check each one
kubectl logs my-app -c main --previous
kubectl logs my-app -c init-db --previous
Key Takeaways
kubectl logsshows stdout/stderr from containers- Use
-fto stream logs in real time - Use
--previousto see logs from crashed containers - Specify
-c <container>for multi-container Pods - Use
--sinceand--tailto limit output volume - Label selectors with
-llet you aggregate logs across Pods