๐ kubectl logs Real-World Use Cases Explained¶
kubectl logs is used to view logs generated by containers in your Kubernetes pods. Logs help you troubleshoot issues, understand behavior, and monitor applications.
๐ Basic Use Cases¶
1. View logs from a pod with a single container¶
kubectl logs nginx
2. Add pod/container name as prefix¶
kubectl logs nginx --prefix
Explanation: Adds a prefix to each line in logs showing [pod-name/container-name], helpful when aggregating logs from multiple containers.
Real-World Example: In CI/CD pipelines or ELK (Elasticsearch, Logstash, Kibana) stacks, prefixes make it easier to trace logs.
3. Limit log size (in bytes)¶
kubectl logs nginx --limit-bytes=500
Explanation: Limits the amount of logs fetched from the pod. Useful for debugging without overloading the terminal.
4. Wait for pod to be ready¶
kubectl logs nginx --pod-running-timeout=20s
Explanation: Useful in CI/CD pipelines or scripting scenarios where pods may still be starting.
๐ง Multi-Container Use Cases¶
5. View logs from all containers in a pod¶
kubectl logs nginx --all-containers=true
6. View logs from all pods in a deployment¶
kubectl logs deployment/nginx --all-pods=true
7. Logs from labelled pods¶
kubectl logs -l app=nginx --all-containers=true
app=nginx. This command gives you logs from all such pods, useful in large apps with multiple replicas. 8. Limit number of concurrent log requests¶
kubectl logs -l app=nginx --max-log-requests=10
Explanation: Prevents overloading kubectl or Kubernetes API server.
๐ Previous Logs¶
9. View logs from previously terminated container¶
kubectl logs -p -c ruby web-1
๐ก Streaming (Live Tail)¶
10. Stream logs and ignore errors¶
kubectl logs nginx -f --ignore-errors=true
11. Stream logs from a specific container¶
kubectl logs -f -c ruby web-1
ruby) is of interest. 12. Stream logs from all containers in all labelled pods¶
kubectl logs -f -l app=nginx --all-containers=true
๐ Time-Based Filtering¶
13. Show only the last 20 lines¶
kubectl logs --tail=20 nginx
14. Show logs written in last 1 hour¶
kubectl logs --since=1h nginx
15. Show logs from a specific timestamp¶
kubectl logs nginx --since-time=2024-08-30T06:00:00Z --timestamps=true
16. Skip TLS verification¶
kubectl logs --insecure-skip-tls-verify-backend nginx
๐ผ Special Resource Types¶
17. Logs from a Job¶
kubectl logs job/hello
18. Logs from a specific container of a deployment¶
kubectl logs deployment/nginx -c nginx-1
๐ Summary Table¶
| Use Case | Command |
|---|---|
| Single Container | kubectl logs pod-name |
| Multi-Container | --all-containers=true |
| Stream Logs | -f |
| Previous Logs | -p |
| Filter by Label | -l app=name |
| Resource Type (Job/Deployment) | job/name, deployment/name |
| Time-based | --since=1h, --since-time= |
| TLS Skip | --insecure-skip-tls-verify-backend |
| Limit Output | --limit-bytes, --tail |