Engineering

Kubectl Logs Command 2026: Complete Guide to Viewing and Tailing Kubernetes Pod Logs

Engineering Team

The kubectl logs command is essential for debugging and monitoring applications running in Kubernetes. Whether you need to troubleshoot a failing pod, stream logs in real-time, or use kubectl tail logs to view recent entries, this comprehensive guide covers everything you need to know about viewing Kubernetes pod logs in 2026.

Quick Reference: Kubectl Logs Cheat Sheet

CommandDescription
kubectl logs pod-nameView all logs from a pod
kubectl logs pod-name --tail=100Kubectl tail logs - last 100 lines
kubectl logs pod-name -fStream logs in real-time
kubectl logs pod-name --since=1hLogs from last hour
kubectl logs pod-name -c containerSpecific container logs
kubectl logs pod-name --previousPrevious container logs
kubectl logs -l app=nginxLogs by label selector
kubectl logs pod-name --timestampsInclude timestamps

What Is the Kubectl Logs Command?

The kubectl logs command retrieves container logs from pods running in your Kubernetes cluster. Containers write their output to stdout and stderr, which Kubernetes captures and makes accessible through this command.

Basic syntax:

kubectl logs [OPTIONS] POD_NAME [-c CONTAINER_NAME]

How it works:

  1. The command connects to the kubelet on the node where the pod runs
  2. Kubelet streams logs from container stdout/stderr
  3. Logs are stored on nodes at /var/log/pods and /var/log/containers
  4. Automatic rotation is managed by the container runtime

The kubectl logs command allows you to:

  • View complete log output from any pod
  • Stream logs in real-time with the follow flag
  • Use kubectl logs tail to show only recent log lines
  • Filter logs by time period
  • Access logs from specific containers in multi-container pods
  • View logs from previous container instances after crashes

Kubectl Logs Command: Basic Usage

View All Logs from a Pod

The simplest usage retrieves all available logs from a pod:

kubectl logs nginx-pod

Output:

10.244.0.1 - - [25/Jan/2026:10:15:32 +0000] "GET / HTTP/1.1" 200 615
10.244.0.1 - - [25/Jan/2026:10:15:33 +0000] "GET /favicon.ico HTTP/1.1" 404 153
10.244.0.1 - - [25/Jan/2026:10:16:01 +0000] "GET /api/health HTTP/1.1" 200 2

View Logs from a Specific Namespace

If your pod is not in the default namespace, specify it with -n:

kubectl logs nginx-pod -n production

View Logs from a Deployment

You can reference pods by their deployment:

kubectl logs deployment/nginx-deployment

This retrieves logs from one pod in the deployment. For all pods, use label selectors (covered below).

View Logs from a Job or CronJob

# Logs from a job
kubectl logs job/backup-job

# Logs from the most recent cronjob execution
kubectl logs job/$(kubectl get jobs --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1].metadata.name}')

Kubectl Tail Logs: Viewing Recent Log Lines

When dealing with applications that generate large amounts of logs, you don’t want to retrieve everything. The kubectl logs tail option limits output to the most recent lines.

Using —tail Flag

The --tail flag specifies how many recent lines to display:

# Show last 50 lines
kubectl logs nginx-pod --tail=50

# Show last 100 lines
kubectl logs api-server --tail=100

# Show last 10 lines from a specific namespace
kubectl logs payment-service -n production --tail=10

Kubectl Tail Logs Examples

Tail logs from a crashing pod:

kubectl logs crashloop-pod --tail=200

Tail logs with timestamps:

kubectl logs nginx-pod --tail=50 --timestamps

Output with timestamps:

2026-01-25T10:15:32.123456789Z 10.244.0.1 - - "GET / HTTP/1.1" 200 615
2026-01-25T10:15:33.234567890Z 10.244.0.1 - - "GET /favicon.ico HTTP/1.1" 404 153

Combining Tail with Other Options

The --tail flag combines well with other options:

# Tail last 100 lines and follow new logs
kubectl logs nginx-pod --tail=100 -f

# Tail last 50 lines from specific container
kubectl logs multi-container-pod -c app --tail=50

# Tail logs from previous container instance
kubectl logs crashed-pod --tail=100 --previous

Kubectl Logs Follow: Real-Time Log Streaming

The -f or --follow flag streams logs in real-time, similar to tail -f on Linux. This is essential for monitoring live application behavior.

Stream Logs in Real-Time

# Follow logs from a pod
kubectl logs -f nginx-pod

# Follow with namespace
kubectl logs -f api-server -n production

# Shorthand syntax
kubectl logs nginx-pod -f

Tail and Follow Together

For the best debugging experience, combine --tail with -f:

# Show last 100 lines, then follow new logs
kubectl logs nginx-pod --tail=100 -f

This shows recent context before streaming new entries.

Stream Logs from Multiple Containers

For pods with sidecars or multiple containers:

# Follow logs from all containers
kubectl logs nginx-pod --all-containers -f

# Follow specific container
kubectl logs nginx-pod -c nginx -f

Stream with Prefix (Kubernetes 1.28+)

In newer Kubernetes versions, add pod/container prefixes:

kubectl logs -l app=nginx -f --prefix

Output:

[pod/nginx-abc123/nginx] 10.244.0.1 - - "GET / HTTP/1.1" 200
[pod/nginx-def456/nginx] 10.244.0.2 - - "GET /api HTTP/1.1" 200

Kubectl Logs Command: Time-Based Filtering

Filter logs by time period using --since or --since-time.

Using —since (Relative Time)

The --since flag accepts relative durations:

# Logs from last hour
kubectl logs nginx-pod --since=1h

# Logs from last 30 minutes
kubectl logs api-server --since=30m

# Logs from last 60 seconds
kubectl logs payment-service --since=60s

# Logs from last 2 hours
kubectl logs database-pod --since=2h

Duration formats:

  • s - seconds (e.g., 60s)
  • m - minutes (e.g., 30m)
  • h - hours (e.g., 2h)

Using —since-time (Absolute Time)

For specific timestamps, use --since-time with RFC3339 format:

# Logs since specific time
kubectl logs nginx-pod --since-time="2026-01-25T10:00:00Z"

# Logs since midnight UTC
kubectl logs api-server --since-time="2026-01-25T00:00:00Z"

Combining Time Filters with Tail

# Last hour of logs, only last 200 lines
kubectl logs nginx-pod --since=1h --tail=200

# Last 30 minutes, followed in real-time
kubectl logs api-server --since=30m -f

Multi-Container Pod Logs

Pods often contain multiple containers (sidecars, init containers). The kubectl logs command requires you to specify which container to target.

List Containers in a Pod

First, identify available containers:

kubectl get pod nginx-pod -o jsonpath='{.spec.containers[*].name}'

Or describe the pod:

kubectl describe pod nginx-pod | grep -A 10 "Containers:"

View Specific Container Logs

Use -c or --container to specify the container:

# Logs from 'nginx' container
kubectl logs nginx-pod -c nginx

# Logs from 'sidecar' container
kubectl logs nginx-pod -c sidecar

# Tail logs from specific container
kubectl logs nginx-pod -c app --tail=100 -f

View All Container Logs

The --all-containers flag retrieves logs from every container:

kubectl logs nginx-pod --all-containers

# With follow
kubectl logs nginx-pod --all-containers -f

# With timestamps to distinguish containers
kubectl logs nginx-pod --all-containers --timestamps

View Init Container Logs

Init containers run before main containers. Access their logs the same way:

kubectl logs nginx-pod -c init-container-name

Viewing Previous Container Logs

When a container crashes and restarts, Kubernetes keeps logs from the previous instance. This is critical for debugging CrashLoopBackOff issues.

Using —previous Flag

# View logs from crashed container
kubectl logs crashed-pod --previous

# Short form
kubectl logs crashed-pod -p

# Previous logs with tail
kubectl logs crashed-pod --previous --tail=100

# Previous logs from specific container
kubectl logs multi-pod -c app --previous

Check Container Restart Count

First, verify if the container has restarted:

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

Or:

kubectl describe pod problematic-pod | grep "Restart Count"

Debugging CrashLoopBackOff

# Step 1: Check pod status
kubectl get pod crashing-pod

# Step 2: View previous logs
kubectl logs crashing-pod --previous --tail=200

# Step 3: Check events
kubectl describe pod crashing-pod | tail -20

# Step 4: Check resource limits
kubectl get pod crashing-pod -o yaml | grep -A 5 resources

Kubectl Logs with Label Selectors

View logs from multiple pods matching a label selector.

Using -l Flag

# Logs from all pods with label app=nginx
kubectl logs -l app=nginx

# Logs from backend pods in production
kubectl logs -l tier=backend -n production

# Multiple label selectors
kubectl logs -l app=api,version=v2

# With tail
kubectl logs -l app=web --tail=50

# With max log requests (default 5)
kubectl logs -l app=nginx --max-log-requests=10

Limitations

The -l selector retrieves logs from multiple pods but has limitations:

  • Cannot use with -f (follow) for multiple pods in older versions
  • Returns logs from all matching pods concatenated
  • Default max of 5 pods (use --max-log-requests to increase)

For better multi-pod log streaming, use stern or kail (covered below).


Node Log Query (Kubernetes 1.27+)

Kubernetes 1.27 introduced the Node Log Query feature, allowing you to view logs from node-level services directly.

Enable Node Log Query

This feature requires the NodeLogQuery feature gate:

# kubelet configuration
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
featureGates:
  NodeLogQuery: true
enableSystemLogQuery: true

Query Node Logs

# View kubelet logs
kubectl get --raw "/api/v1/nodes/node-name/proxy/logs/?query=kubelet"

# View container runtime logs
kubectl get --raw "/api/v1/nodes/node-name/proxy/logs/?query=containerd"

# Filter by time
kubectl get --raw "/api/v1/nodes/node-name/proxy/logs/?query=kubelet&sinceTime=2026-01-25T00:00:00Z"

Use Cases for Node Log Query

ServiceQuery
Kubelet?query=kubelet
Container Runtime?query=containerd
Kube Proxy?query=kube-proxy
System Journal?query=journal

Exporting Logs to Files

Save logs to files for analysis or sharing.

Basic Export

# Export to file
kubectl logs nginx-pod > nginx-logs.txt

# Export with timestamps
kubectl logs nginx-pod --timestamps > nginx-logs.txt

# Export last 1000 lines
kubectl logs api-server --tail=1000 > api-logs.txt

Export with Metadata

Include pod and timestamp information:

# Add header with pod info
echo "=== Logs for nginx-pod $(date) ===" > debug-logs.txt
kubectl logs nginx-pod >> debug-logs.txt

Export All Container Logs

kubectl logs multi-pod --all-containers > all-container-logs.txt

Export Logs from All Pods in Deployment

#!/bin/bash
DEPLOYMENT="api-server"
NAMESPACE="production"

for pod in $(kubectl get pods -l app=$DEPLOYMENT -n $NAMESPACE -o name); do
  echo "=== $pod ===" >> deployment-logs.txt
  kubectl logs $pod -n $NAMESPACE --tail=500 >> deployment-logs.txt
done

Filtering Logs with Grep

Combine kubectl logs with grep for powerful filtering.

Search for Errors

# Find error messages
kubectl logs api-server | grep -i error

# Find errors with context (5 lines before/after)
kubectl logs api-server | grep -B 5 -A 5 "ERROR"

# Case-insensitive search
kubectl logs nginx-pod | grep -i "failed\|error\|exception"

Filter Specific Patterns

# Find HTTP 500 errors
kubectl logs nginx-pod | grep "HTTP/1.1\" 5"

# Find specific user activity
kubectl logs api-server | grep "user_id=12345"

# Find slow requests (over 1 second)
kubectl logs api-server | grep -E "duration=[0-9]{4,}ms"

# Find JSON errors with jq
kubectl logs api-server | grep "^{" | jq 'select(.level == "error")'

Real-Time Filtered Streaming

# Stream only error logs
kubectl logs -f api-server | grep --line-buffered -i error

# Stream specific request paths
kubectl logs -f nginx-pod | grep --line-buffered "/api/v2"

Note: Use --line-buffered with grep when piping from -f to see output immediately.


Stern: Multi-Pod Log Streaming

Stern is a powerful tool for tailing logs from multiple pods simultaneously. It’s invaluable for debugging microservices in 2026.

Install Stern

macOS (Homebrew):

brew install stern

Linux:

# Download latest release
curl -LO https://github.com/stern/stern/releases/latest/download/stern_linux_amd64.tar.gz
tar xzf stern_linux_amd64.tar.gz
sudo mv stern /usr/local/bin/

Windows (Chocolatey):

choco install stern

Stern Usage Examples

# Stream logs from all pods matching pattern
stern nginx

# Stream from specific namespace
stern api-server -n production

# Stream from pods with label
stern -l app=backend

# Include timestamps
stern nginx -t

# Filter by container name
stern nginx -c nginx

# Exclude specific containers
stern nginx --exclude-container sidecar

# Show last 10 lines, then follow
stern nginx --tail 10

# Output as JSON
stern nginx -o json

Stern vs Kubectl Logs

Featurekubectl logsstern
Multi-pod streamingLimitedYes
Color-coded outputNoYes
Pod name prefixManualAutomatic
Regex pod matchingNoYes
Container filteringManualBuilt-in
JSON outputNoYes

Kail: Kubernetes Tail

Kail is another excellent tool for streaming logs from multiple sources.

Install Kail

# macOS
brew install boz/repo/kail

# Go install
go install github.com/boz/kail/cmd/kail@latest

Kail Usage Examples

# Stream all logs in namespace
kail -n production

# Stream logs from specific deployment
kail --deploy api-server

# Stream logs from multiple labels
kail -l app=frontend -l app=backend

# Stream from specific service
kail --svc payment-service

# Exclude system namespaces
kail --ignore-ns kube-system

Kubetail: Simple Multi-Pod Tailing

Kubetail is a bash script for tailing logs from multiple pods.

Install Kubetail

# macOS
brew install kubetail

# Manual
curl -o /usr/local/bin/kubetail https://raw.githubusercontent.com/johanhaleby/kubetail/master/kubetail
chmod +x /usr/local/bin/kubetail

Kubetail Usage

# Tail all pods matching pattern
kubetail nginx

# Specific namespace
kubetail api-server -n production

# Follow with color
kubetail payment -c

Kubectl Logs Command Reference

Complete Flags Reference

FlagShortDescription
--follow-fStream logs in real-time
--previous-pShow logs from previous container instance
--container-cSpecify container name
--tailNumber of recent lines to show
--sinceShow logs newer than relative duration
--since-timeShow logs newer than absolute time (RFC3339)
--timestampsInclude timestamps in output
--all-containersShow logs from all containers
--selector-lLabel selector for pods
--namespace-nSpecify namespace
--limit-bytesMaximum bytes of logs to return
--pod-running-timeoutTimeout for pod to be running
--prefixPrefix each log line with pod/container name
--max-log-requestsMax number of concurrent logs to request (default 5)

Common Command Combinations

# Debug a crashing pod
kubectl logs crashed-pod --previous --tail=200

# Monitor deployment rollout
kubectl logs -l app=myapp --all-containers --prefix -f

# Export recent error logs
kubectl logs api-server --since=1h | grep -i error > errors.txt

# Stream with context
kubectl logs nginx-pod --tail=50 -f --timestamps

# Debug across namespaces
kubectl logs -l app=api --all-namespaces --max-log-requests=20

Kubernetes Logging Best Practices 2026

1. Log to stdout/stderr

Configure applications to log to stdout/stderr, not files:

# Example: Configure nginx to log to stdout
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
data:
  nginx.conf: |
    error_log /dev/stderr;
    access_log /dev/stdout;

2. Use Structured Logging (JSON)

Use JSON logs for easier parsing and aggregation:

{"timestamp":"2026-01-25T10:15:32Z","level":"INFO","message":"Request processed","duration_ms":45,"request_id":"abc123"}

Parse JSON logs with jq:

kubectl logs api-server | grep "^{" | jq '.level, .message'

3. Add Request IDs for Distributed Tracing

Include correlation IDs for tracing requests across services:

kubectl logs api-server | grep "request_id=abc123"

4. Implement Log Rotation

Prevent log storage from consuming disk space:

# Container runtime log rotation (containerd)
[plugins."io.containerd.grpc.v1.cri".containerd]
  max-container-log-line-size = 16384

# Kubelet configuration
containerLogMaxSize: "10Mi"
containerLogMaxFiles: 5

5. Use RBAC for Log Access

Control who can access logs:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: log-reader
  namespace: production
rules:
  - apiGroups: [""]
    resources: ["pods/log"]
    verbs: ["get", "list"]

6. Implement Centralized Logging

For production, don’t rely solely on kubectl logs. Implement a logging stack:

SolutionTypeBest For
Grafana LokiOpen SourceKubernetes-native, cost-effective
EFK StackOpen SourceFull-text search, analytics
DatadogCommercialFull observability platform
SplunkCommercialEnterprise, compliance

Troubleshooting Common Issues

”Error from server: container not found”

The pod may have multiple containers. List them and specify one:

kubectl get pod pod-name -o jsonpath='{.spec.containers[*].name}'
kubectl logs pod-name -c container-name

No Logs Appearing

  1. Check if pod is running:

    kubectl get pod pod-name
  2. Check container status:

    kubectl describe pod pod-name
  3. Verify application writes to stdout/stderr: Some applications log to files instead of stdout. Configure them to log to stdout or use a sidecar.

”Error from server: pod not found”

Verify namespace:

kubectl get pods --all-namespaces | grep pod-name
kubectl logs pod-name -n correct-namespace

Logs Truncated or Missing

Kubernetes rotates logs when they exceed size limits. For persistent logging, implement a centralized logging solution.

Check kubelet log settings:

# View kubelet config
kubectl get configmap kubelet-config -n kube-system -o yaml | grep -A 2 containerLog

Previous Logs Not Available

Previous logs are only kept if the container restarted. Check restart count:

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

If restart count is 0, there are no previous logs.

”Unable to retrieve container logs” for large logs

Use --limit-bytes to prevent memory issues:

kubectl logs large-log-pod --limit-bytes=1000000

Conclusion

The kubectl logs command remains your primary tool for debugging Kubernetes applications in 2026. Key takeaways:

  • Use kubectl logs pod-name for basic log viewing
  • Use --tail for kubectl tail logs to limit output to recent lines
  • Use -f to stream logs in real-time
  • Use --previous to debug crashed containers
  • Use --since for time-based filtering
  • Use --prefix for multi-pod identification (K8s 1.28+)
  • Use Node Log Query for node-level logs (K8s 1.27+)
  • Use stern or kail for multi-pod log streaming
  • Implement centralized logging for production workloads

Mastering these kubectl logs techniques will significantly improve your Kubernetes troubleshooting efficiency in 2026.


Need help with Kubernetes monitoring and logging? Our DevOps consulting team can help you implement production-ready observability solutions.

Book a free 30-minute consultation to discuss your Kubernetes logging requirements.

Chat with real humans
Chat on WhatsApp