Logs & Debugging

Inspect Pods with kubectl logs, describe, exec, and events to diagnose problems.

When something misbehaves, a handful of kubectl commands cover almost all debugging.

The debugging toolkit

  • kubectl logs <pod> — read a container's stdout/stderr. Add -f to follow, --previous for a crashed instance, and -c <container> to pick a container.
  • kubectl describe pod <pod> — shows events, probe results, and why a Pod is Pending or crashing.
  • kubectl exec -it <pod> -- sh — open a shell inside a running container.
  • kubectl get events --sort-by=.lastTimestamp — recent cluster events.

Production logging

Container logs are ephemeral — they vanish with the Pod. In production, a log agent (a DaemonSet like Fluent Bit) ships logs to a central store such as Elasticsearch or Loki.

Example

Example · bash
# Follow logs from a specific container in a Pod
kubectl logs -f my-app -c app

# Logs from the previous, crashed instance
kubectl logs my-app --previous

# Full detail: events, status, probes
kubectl describe pod my-app

# Open a shell to poke around
kubectl exec -it my-app -- sh

When to use it

  • An SRE uses kubectl logs with --since=1h to retrieve the last hour of logs from a crashing pod after being paged for an incident.
  • A team ships all pod logs to a central Elasticsearch cluster using a Fluentd DaemonSet, enabling cross-service log correlation in Kibana.
  • A developer uses kubectl logs -f to stream live log output from a pod while testing a new feature in a development environment.

More examples

Basic and filtered log retrieval

Shows the most common log retrieval patterns: tail, follow, time filter, and targeting a specific container.

Example · bash
# Last 100 lines
kubectl logs my-pod --tail=100

# Follow live
kubectl logs my-pod -f

# Last hour only
kubectl logs my-pod --since=1h

# Specific container in multi-container pod
kubectl logs my-pod -c sidecar

Logs from a crashed pod

Uses --previous to retrieve logs from the last crashed container instance, essential for diagnosing crash-loop causes.

Example · bash
# Get logs from the previous (crashed) container instance
kubectl logs my-pod --previous

# Combined with tail to see crash output
kubectl logs my-pod --previous --tail=50

Aggregate logs from a Deployment

Streams logs from all web pods simultaneously using -l (label selector) or the stern tool for better multi-pod log aggregation.

Example · bash
# Stream logs from all pods with a label selector
kubectl logs -l app=web -f --max-log-requests=10

# Or using stern (popular multi-pod log tool)
stern web --tail=20

Discussion

  • Be the first to comment on this lesson.
Logs & Debugging — Kubernetes | SoundsCode