Logs, exec, events and port-forward

Kubernetes · Essentials · 10 min

These five commands solve most day-to-day 'why isn't it working' questions.

Your basic toolkit:

  • kubectl logs pod/web-abc prints a container's stdout/stderr. -f follows, --since=10m limits, -c name picks a container, --previous shows the last crashed instance, the key to crash loops. kubectl logs deploy/web picks one pod; -l app=web --prefix reads many.
  • kubectl describe pod web-abc: state, restart count, last termination reason (e.g. OOMKilled), and events.
  • kubectl events --for pod/web-abc or kubectl get events --sort-by=.lastTimestamp: what the scheduler, kubelet and controllers reported. Events expire after about an hour.
  • kubectl exec -it web-abc -- sh opens a shell inside the container, if the image has one.
  • kubectl port-forward pod/web-abc 8080:80 reaches a pod or Service from your laptop without exposing it.
  • kubectl debug -it web-abc --image=busybox:1.37 --target=app adds an ephemeral container sharing the pod's namespaces: debugging tools for distroless images that have no shell.
  • kubectl cp web-abc:/tmp/dump.txt ./dump.txt copies files (needs tar in the container).

Logs are kept only for the current and previous container on the node; for history, ship logs to a central system (Loki, Elasticsearch, CloudWatch).

Example

kubectl get pods
# web-7f9c-x2   0/1   CrashLoopBackOff   5   4m

kubectl logs web-7f9c-x2 --previous      # output of the crashed run
kubectl describe pod web-7f9c-x2 | sed -n '/Last State/,/Exit Code/p'
#   Last State: Terminated  Reason: Error  Exit Code: 1

kubectl events --for pod/web-7f9c-x2
kubectl exec -it deploy/web -- env | grep DB_
kubectl port-forward svc/web 8080:80
kubectl debug -it web-7f9c-x2 --image=busybox:1.37 --target=app -- sh

Remember

  • logs --previous shows why the last container died
  • describe and events explain scheduling and startup problems
  • kubectl debug adds tools to minimal images without rebuilding

Watch out for

  • Reading logs of the fresh container in a crash loop instead of --previous.

Check yourself

  1. A pod restarts every minute. Which command most directly shows what the crashed container printed?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/