kubectl logs Command Reference and Documentation
The kubectl logs command retrieves container logs from Kubernetes pods. It supports real-time log streaming with -f, time-based filtering with --since, viewing previous container instances with --previous, and accessing logs from specific containers in multi-container pods using -c.
Quick Reference
| Flag/Option | Description | Example |
|---|---|---|
kubectl logs <pod> | View pod logs | kubectl logs nginx-pod |
-f, --follow | Stream logs in real-time | kubectl logs -f nginx-pod |
-c <container> | Specify container in pod | kubectl logs pod -c nginx |
--previous | Logs from previous container | kubectl logs --previous pod |
--since=<duration> | Logs since time (1h, 5m, 30s) | kubectl logs --since=1h pod |
--since-time=<RFC3339> | Logs since timestamp | kubectl logs --since-time=2024-01-15T10:00:00Z pod |
--tail=<n> | Show last n lines | kubectl logs --tail=100 pod |
--timestamps | Add timestamps to logs | kubectl logs --timestamps pod |
--all-containers | Logs from all containers | kubectl logs --all-containers pod |
-l <label> | Logs from pods by label | kubectl logs -l app=nginx |
--limit-bytes=<n> | Limit log output size | kubectl logs --limit-bytes=1048576 pod |
-n <namespace> | Specify namespace | kubectl logs -n prod pod |
What is kubectl logs?
kubectl logs is the standard command for retrieving container logs from Kubernetes pods. It connects to the kubelet on the node where the pod runs and streams logs from container stdout/stderr. The command works with running pods, completed pods, and can access logs from crashed containers using the --previous flag.
Logs are stored on each node at /var/log/pods and /var/log/containers, with automatic rotation managed by the container runtime. For centralized logging across clusters, consider using comprehensive infrastructure monitoring solutions or monitoring Kubernetes with OpenTelemetry.
Basic Commands
View Pod Logs
Display logs from a single pod:
kubectl logs nginx-pod
For pods in a specific namespace:
kubectl logs -n production nginx-pod
View Container Logs
For multi-container pods, specify the container name with -c:
kubectl logs nginx-pod -c nginx-container
List all containers in a pod:
kubectl get pod nginx-pod -o jsonpath='{.spec.containers[*].name}'
Follow Logs in Real-Time
Stream logs continuously using -f or --follow:
kubectl logs -f nginx-pod
Watch logs from a specific container:
kubectl logs -f nginx-pod -c nginx-container
View Logs with Timestamps
Add timestamps to each log line:
kubectl logs --timestamps nginx-pod
Timestamps use RFC3339 format:
2024-01-15T10:30:45.123456789Z log message here
Time-Based Filtering
Logs Since Duration
View logs from the last hour, minutes, or seconds:
# Last hour
kubectl logs --since=1h nginx-pod
# Last 30 minutes
kubectl logs --since=30m nginx-pod
# Last 60 seconds
kubectl logs --since=60s nginx-pod
Logs Since Specific Time
Filter logs from an exact timestamp using RFC3339 format:
kubectl logs --since-time=2024-01-15T10:00:00Z nginx-pod
Combine with follow for recent streaming:
kubectl logs --since=5m -f nginx-pod
Limiting Output
Tail Specific Number of Lines
Show only the last N lines:
# Last 100 lines
kubectl logs --tail=100 nginx-pod
# Last 10 lines
kubectl logs --tail=10 nginx-pod
Combine with follow to tail and stream:
kubectl logs --tail=50 -f nginx-pod
Limit Bytes
Restrict output size in bytes:
kubectl logs --limit-bytes=1048576 nginx-pod # 1MB limit
Previous Container Logs
View Logs from Crashed Containers
Access logs from the previous container instance (useful for CrashLoopBackOff):
kubectl logs --previous nginx-pod
With specific container:
kubectl logs --previous nginx-pod -c nginx-container
Check if previous container exists:
kubectl get pod nginx-pod -o jsonpath='{.status.containerStatuses[0].lastState}'
Multiple Pods and Containers
All Containers in a Pod
View logs from all containers simultaneously:
kubectl logs nginx-pod --all-containers=true
With timestamps and streaming:
kubectl logs nginx-pod --all-containers=true --timestamps -f
Logs by Label Selector
Get logs from all pods matching a label:
kubectl logs -l app=nginx
Multiple label conditions:
kubectl logs -l app=nginx,environment=production
Combine with other flags:
kubectl logs -l app=nginx --tail=50 -f
Multiple Pods with stern
For advanced multi-pod logging, use stern:
# Install stern
brew install stern
# View logs from multiple pods
stern nginx
# Filter by namespace and container
stern -n production -c nginx-container nginx
Filtering and Searching Logs
Using grep
Filter logs for specific patterns:
# Find ERROR lines
kubectl logs nginx-pod | grep "ERROR"
# Case-insensitive search
kubectl logs nginx-pod | grep -i "error"
# Exclude lines
kubectl logs nginx-pod | grep -v "DEBUG"
# Show context (3 lines before and after)
kubectl logs nginx-pod | grep -C 3 "ERROR"
Using jq for JSON Logs
Parse structured JSON logs:
# Extract specific fields
kubectl logs nginx-pod | jq -r '.level + " " + .message'
# Filter by log level
kubectl logs nginx-pod | jq 'select(.level == "ERROR")'
# Count errors
kubectl logs nginx-pod | jq 'select(.level == "ERROR")' | wc -l
Saving Logs to File
Redirect to File
Save logs for offline analysis:
kubectl logs nginx-pod > pod-logs.txt
With timestamp in filename:
kubectl logs nginx-pod > "nginx-logs-$(date +%Y%m%d-%H%M%S).txt"
Save Logs from Multiple Pods
for pod in $(kubectl get pods -l app=nginx -o name); do
kubectl logs $pod > "${pod}-logs.txt"
done
Stream Logs to File
Continuously save logs while following:
kubectl logs -f nginx-pod > nginx-live.log
Troubleshooting
Pod is CrashLoopBackOff
View logs from the crashed container:
kubectl logs --previous nginx-pod
Check pod status and restart count:
kubectl get pod nginx-pod
kubectl describe pod nginx-pod | grep -A 5 "State:"
No Logs Appearing
Check if pod is running:
kubectl get pod nginx-pod
Verify container is logging to stdout/stderr:
kubectl exec nginx-pod -- sh -c "ls -la /proc/1/fd/"
Check for log file location issues:
Applications must log to stdout (fd 1) or stderr (fd 2), not to files.
Container Not Found Error
List all containers in the pod:
kubectl get pod nginx-pod -o jsonpath='{.spec.containers[*].name}'
Use correct container name:
kubectl logs nginx-pod -c correct-container-name
Logs Truncated or Missing
Check log file size limits on nodes:
kubectl get nodes -o yaml | grep -A 5 "kubelet"
Default limits are typically 10MB per container log file.
Permission Denied
Verify you have proper RBAC permissions:
kubectl auth can-i get pods/log
kubectl auth can-i get pods/log --as=system:serviceaccount:default:my-sa
Log Storage and Rotation
Where Logs are Stored
Kubernetes stores container logs on each node:
/var/log/pods/- Pod logs organized by namespace and pod name/var/log/containers/- Symlinks to pod logs
View log file directly on node:
kubectl debug node/node-name -it --image=ubuntu
ls /var/log/pods
Log Rotation
Kubernetes automatically rotates logs based on:
- Max file size: Default 10MB per container
- Max files: Default 5 files per container
Configure in kubelet:
--container-log-max-size=10Mi
--container-log-max-files=5
Termination Message
Containers can write termination messages:
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
containers:
- name: nginx
image: nginx
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
View termination message:
kubectl get pod nginx-pod -o jsonpath='{.status.containerStatuses[0].lastState.terminated.message}'
Advanced Techniques
Watch Logs with watch Command
Refresh logs every 5 seconds:
watch -n 5 'kubectl logs nginx-pod --tail=20'
Combining Multiple Flags
# Last 50 lines from past hour with timestamps
kubectl logs nginx-pod --since=1h --tail=50 --timestamps
# Follow logs from specific container with time filter
kubectl logs -f nginx-pod -c nginx-container --since=10m
# Previous container logs with timestamps
kubectl logs --previous nginx-pod --timestamps
Collecting Kubernetes logs in Uptrace
Uptrace is an open-source APM tool that supports collecting and analyzing logs from Kubernetes clusters. Here's how you can set it up:
- Deploy Uptrace in your Kubernetes cluster or set it up externally.
- Configure a log collection agent like Fluent Bit:
apiVersion: v1
kind: ConfigMap
metadata:
name: fluent-bit-config
namespace: logging
data:
fluent-bit.conf: |
[SERVICE]
Flush 5
Daemon Off
Log_Level info
Parsers_File parsers.conf
[INPUT]
Name tail
Path /var/log/containers/*.log
Parser docker
Tag kube.*
Refresh_Interval 5
Mem_Buf_Limit 5MB
Skip_Long_Lines On
[FILTER]
Name kubernetes
Match kube.*
Kube_URL https://kubernetes.default.svc:443
Kube_CA_File /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
Kube_Token_File /var/run/secrets/kubernetes.io/serviceaccount/token
Merge_Log On
K8S-Logging.Parser On
[OUTPUT]
Name http
Match *
Host uptrace-host
Port 14318
URI /api/v1/logs
Format json
Json_date_key timestamp
- Deploy the log collector and configure Uptrace to receive and process the logs.
- Use the Uptrace UI to search, filter, and analyze your Kubernetes logs.
FAQ
How do I view logs from all containers in a pod?
Use the --all-containers flag:
kubectl logs nginx-pod --all-containers=true
How do I follow logs in real-time?
Use -f or --follow:
kubectl logs -f nginx-pod
How can I see logs from a crashed pod?
Use the --previous flag to view logs from the previous container instance:
kubectl logs --previous nginx-pod
How do I filter logs by time range?
Use --since for duration or --since-time for exact timestamp:
kubectl logs nginx-pod --since=1h
kubectl logs nginx-pod --since-time=2024-01-15T10:00:00Z
Can I get logs from multiple pods at once?
Yes, use label selectors with -l:
kubectl logs -l app=nginx
For more advanced multi-pod logging, use stern.
How do I view logs from a specific container?
Use the -c flag with the container name:
kubectl logs nginx-pod -c nginx-container
How can I limit the number of log lines?
Use --tail to show last N lines:
kubectl logs nginx-pod --tail=100
How do I save logs to a file?
Redirect output to a file:
kubectl logs nginx-pod > pod-logs.txt
Can I view logs with timestamps?
Yes, use the --timestamps flag:
kubectl logs nginx-pod --timestamps
How do I clear kubectl logs?
kubectl doesn't clear logs. Logs are managed by the container runtime and automatically rotated. To clear logs manually, you need node access:
kubectl debug node/node-name -it --image=ubuntu
rm /var/log/pods/namespace_pod-name_uid/container-name/*.log
How do I view logs from a specific namespace?
Use the -n or --namespace flag:
kubectl logs -n production nginx-pod
Where is the kubectl logs documentation?
Official Kubernetes documentation for kubectl logs: kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs
Can I view node logs with kubectl?
Node-level logs require accessing the node directly:
kubectl debug node/node-name -it --image=ubuntu
journalctl -u kubelet
You may also be interested in:
- Uptrace Documentation - Explore the full capabilities of Uptrace for log management, distributed tracing, and metrics in your Kubernetes environment.
- Forever free OpenTelemetry APM
- Distributed Tracing in Kubernetes
- Open source log management tools