Skip to content
Kubernetes tools · Chapter 9 of 20 Day 7: Logs and Debugging

Day 7: Logs and Debugging

Goal: Follow and filter the logs of many Pods at once, find the logs of crashed containers, examine containers without a shell with kubectl debug, and debug copies of Pods and nodes · Duration: approx. 80 min · Prerequisite: Day 6

Briefing

  • kubectl logs reads one container of one Pod. With three replicas, you need three commands, and you have to find new Pods after a rollout yourself. stern follows all Pods whose name matches a regular expression, or all Pods with a label, and picks up new Pods automatically.
  • If a container crashes, the kubelet restarts it. The logs of the dead container stay only briefly: the kubelet keeps exactly one terminated predecessor per container.
  • Many images have no shell (scratch, distroless). kubectl exec … -- sh then fails. kubectl debug attaches an ephemeral container with tools to the running Pod, copies a Pod with a changed start command, or starts a Pod on a node with access to its file system.
  • Everything you type and see in a debug container ends up in its logs. kubectl says so itself on every call, and it applies to passwords too, as Drill 4 shows.
Task Tool
Logs of many Pods live stern <regex> or stern -l <label>
Filter logs stern -i <regex>, -e <regex>
Logs of the crashed container kubectl logs --previous
Shell in a container without a shell kubectl debug -it <pod> --image=… --target=<container>
Rebuild a Pod with a different command kubectl debug <pod> --copy-to=<name> --container=… -- <command>
Look at a node kubectl debug node/<node> -it --image=… --profile=sysadmin

Drill 1: Installing stern

ARCH=$(dpkg --print-architecture)
curl -sL https://github.com/stern/stern/releases/download/v1.35.0/stern_1.35.0_linux_${ARCH}.tar.gz | tar xz -C /tmp stern
sudo install /tmp/stern /usr/local/bin/stern
stern --version

Expected:

version: 1.35.0
commit: 37fcd4cfc29f61dcd1cdfdb68de8a75e8b33c5fe
built at: 2026-10-22T13:52:12Z

Alternative: stern is also available as a Krew plugin (kubectl krew install stern, called as kubectl stern). The binary is the same.

Generate some traffic on web and read the logs of all three Pods:

kubectl -n laden exec werkbank -- sh -c 'for i in 1 2 3 4 5 6; do wget -qO- http://web >/dev/null; done'
stern -n laden web --since 1m --no-follow

Expected (excerpt):

+ web-67649cfddb-fzrd6 › nginx
web-67649cfddb-fzrd6 nginx 10.244.2.127 - - [24/Nov/2026:13:09:54 +0000] "GET / HTTP/1.1" 200 896 "-" "kube-probe/1.37" "-"
web-67649cfddb-fzrd6 nginx 10.244.2.14 - - [24/Nov/2026:13:10:12 +0000] "GET / HTTP/1.1" 200 896 "-" "Wget" "-"
web-67649cfddb-fzrd6 nginx 10.244.2.14 - - [24/Nov/2026:13:10:13 +0000] "GET / HTTP/1.1" 200 896 "-" "Wget" "-"
- web-67649cfddb-fzrd6 › nginx

Each line starts with the Pod and container, in color in the terminal. The lines with + and - show when stern starts and stops following a container; they go to stderr. 10.244.2.14 is the werkbank, and kube-probe are the kubelet’s readiness checks. Without --no-follow, stern keeps running until you press Ctrl-C.

For comparison, kubectl alone:

kubectl -n laden logs -l app=web --prefix --tail=1

Expected:

[pod/web-67649cfddb-6d48k/nginx] 10.244.2.127 - - [24/Nov/2026:13:15:32 +0000] "GET / HTTP/1.1" 200 896 "-" "kube-probe/1.37" "-"
[pod/web-67649cfddb-fzrd6/nginx] 10.244.2.127 - - [24/Nov/2026:13:15:24 +0000] "GET / HTTP/1.1" 200 896 "-" "kube-probe/1.37" "-"
[pod/web-67649cfddb-tggck/nginx] 10.244.1.209 - - [24/Nov/2026:13:15:28 +0000] "GET / HTTP/1.1" 200 896 "-" "kube-probe/1.37" "-"

That works too, but it follows at most five Pods at the same time (--max-log-requests) and does not notice Pods that are added after the start. During a rollout, kubectl logs -f loses track; stern does not.

Save your progress? Sign up for free

Drill 2: A Checkout That Crashes

For the rest of the day, the shop needs a checkout, kasse, with a bug. It prints a receipt every two seconds, now and then reports a slow printer, and writes an end-of-day closing at the twelfth receipt. That is where it fails.

mkdir -p ~/werkzeuge/tag07 && cd ~/werkzeuge/tag07
cat > kasse.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kasse
  namespace: laden
  labels: {app: kasse, tier: backend}
spec:
  replicas: 2
  selector:
    matchLabels: {app: kasse}
  template:
    metadata:
      labels: {app: kasse, tier: backend}
    spec:
      containers:
      - name: kasse
        image: busybox:1.37.0
        command:
        - sh
        - -c
        - |
          i=0
          while true; do
            i=$((i+1))
            echo "$(date -Iseconds) INFO bon=$i summe=$((i*7)) EUR"
            [ $((i%5)) -eq 0 ] && echo "$(date -Iseconds) WARN drucker langsam"
            if [ $i -eq 12 ]; then
              echo "$(date -Iseconds) INFO tagesabschluss nach /daten/abschluss.log"
              echo "bons=$i" >> /daten/abschluss.log || { echo "$(date -Iseconds) ERROR tagesabschluss fehlgeschlagen" >&2; exit 3; }
            fi
            sleep 2
          done
EOF
kubectl apply -f kasse.yaml

Wait two minutes and take a look:

kubectl -n laden get pods -l app=kasse

Expected (counters and times will differ):

NAME                    READY   STATUS   RESTARTS      AGE
kasse-bccf54c45-fwznj   0/1     Error    3 (56s ago)   2m17s
kasse-bccf54c45-z6f76   0/1     Error    3 (52s ago)   2m17s

Depending on the moment, it says Running, Error or CrashLoopBackOff: the container runs for about 24 seconds, dies, and the kubelet waits longer before each restart (10 s, 20 s, 40 s … up to 5 min).

Save your progress? Sign up for free

Drill 3: The Logs of the Dead

First search for errors with stern:

stern -n laden kasse --since 5m --no-follow --include ERROR 2>/dev/null

Expected:

kasse-bccf54c45-fwznj kasse 2026-11-24T13:12:45+00:00 ERROR tagesabschluss fehlgeschlagen
kasse-bccf54c45-z6f76 kasse 2026-11-24T13:12:48+00:00 ERROR tagesabschluss fehlgeschlagen

Now you know that something fails. Why is not in these lines. Reverse the filter and hide only the noise:

stern -n laden kasse --since 30s --no-follow --exclude INFO 2>/dev/null

Expected (excerpt):

kasse-bccf54c45-fwznj kasse 2026-11-24T13:12:31+00:00 WARN drucker langsam
kasse-bccf54c45-fwznj kasse 2026-11-24T13:12:41+00:00 WARN drucker langsam
kasse-bccf54c45-fwznj kasse sh: can't create /daten/abschluss.log: nonexistent directory
kasse-bccf54c45-fwznj kasse 2026-11-24T13:12:45+00:00 ERROR tagesabschluss fehlgeschlagen

There is the cause: the directory /daten does not exist. The line comes from the shell, not from the application, and therefore has neither a timestamp nor a level. A filter on ERROR would never have shown it. That is the lesson of this drill: first exclude what you know, instead of only including what you expect.

Now the same with kubectl. Whether you need --previous depends on the state of the container:

P=$(kubectl -n laden get pods -l app=kasse -o name | head -1)
kubectl -n laden get $P -o jsonpath='{.status.containerStatuses[0].state}{"\n"}'
kubectl -n laden logs $P --tail=3

Expected, as long as the container is dead and waiting for the restart:

{"terminated":{"containerID":"containerd://078a4c05…","exitCode":3,"finishedAt":"2026-11-24T13:12:45Z","reason":"Error","startedAt":"2026-11-24T13:12:23Z"}}
sh: can't create /daten/abschluss.log: nonexistent directory
2026-11-24T13:12:45+00:00 INFO tagesabschluss nach /daten/abschluss.log
2026-11-24T13:12:45+00:00 ERROR tagesabschluss fehlgeschlagen

In this state, the dead container is still the current one, and kubectl logs is enough. --previous would point to the container before it here, and the kubelet has already cleaned that one up:

kubectl -n laden logs $P --previous

Expected in this state:

unable to retrieve container logs for containerd://4d000bcded57e7c6f2f59aac720316145e8e412d3cc706100b53a944fe6ef812

As soon as the container has restarted (state.running), the one that just died is the predecessor, and kubectl logs $P --previous shows the three lines from above. So remember: exit code and reason are always in the status (lastState.terminated or state.terminated), the logs only for the most recent dead container. If you need logs for longer, you have to collect them (Loki, Fluent Bit, see Enterprise Note).

By the way, the line order above is not the order of output: stdout and stderr are buffered separately, and with the same timestamp, the stderr line can appear first.

Save your progress? Sign up for free

Drill 4: A Container Without a Shell

The api Pods run with traefik/whoami, an image that consists of a single program only:

A=$(kubectl -n laden get pods -l app=api -o jsonpath='{.items[0].metadata.name}')
kubectl -n laden exec $A -- sh -c true

Expected (shortened):

error: Internal error occurred: … exec: "sh": executable file not found in $PATH

kubectl debug attaches an additional container with busybox to the same Pod. --target puts it into the process namespace of the container whoami, so you see its processes. Interactively, you call kubectl -n laden debug -it $A --image=busybox:1.37.0 --target=whoami -- sh and type the commands into the shell. To make the output reproducible here, you pass them directly:

kubectl -n laden debug -i $A --image=busybox:1.37.0 --target=whoami --profile=general -- \
  sh -c 'ps; tr "\0" "\n" < /proc/1/environ | grep DB_; ls /proc/1/root/'

Expected:

Targeting container "whoami". If you don't see processes from this container it may be because the container runtime doesn't support this feature.
Defaulting debug container name to debugger-m8snk.
All commands and output from this session will be recorded in container logs, including credentials and sensitive information passed through the command prompt.
If you don't see a command prompt, try pressing enter.

The commands have often finished before kubectl has connected; then their output is missing here. It is in the log of the debug container (take the name from the second line):

kubectl -n laden logs $A -c debugger-m8snk

Expected:

PID   USER     TIME  COMMAND
    1 root      0:00 /whoami --port 8080
   24 root      0:00 sh -c ps; tr "\0" "\n" < /proc/1/environ | grep DB_; ls /proc/1/root/
   36 root      0:00 ps
DB_PASSWORD=lab-geheim-123
dev
etc
proc
product_name
product_uuid
sys
usr
var
whoami

Three things happened:

  1. ps shows /whoami as process 1: you are in the process namespace of the target container.
  2. Through /proc/1/environ, you read the environment of whoami, including the password from the Secret. Whoever may create ephemeral containers gets at every Secret that is in the Pod as an environment variable, even without read permission on Secrets.
  3. /proc/1/root/ is the file system of the target container. This way you read files of an image that has no cat.

The debug container remains part of the Pod even after its command has finished. It cannot be removed; only a new Pod is clean again:

kubectl -n laden get pod $A -o jsonpath='{range .spec.ephemeralContainers[*]}{.name} {.image} {.targetContainerName}{"\n"}{end}'

Expected:

debugger-m8snk busybox:1.37.0 whoami

And stern sees it too. With -E debugger, you hide such containers:

stern -n laden api --tail 1 --no-follow -E debugger 2>/dev/null

Who may do this? The permission is called pods/ephemeralcontainers:

kubectl auth can-i patch pods/ephemeralcontainers -n laden --as=system:serviceaccount:laden:kasse
kubectl auth can-i patch pods/ephemeralcontainers -n laden --as=system:serviceaccount:headlamp:betrachter

Expected:

yes
no

The built-in role edit from the Challenge of Day 6 contains it, view does not.

Save your progress? Sign up for free

Drill 5: Debugging a Copy

The checkout dies after 24 seconds. It is hard to get into a dying container. So you build a copy that simply sleeps instead of running the checkout program:

K=$(kubectl -n laden get pods -l app=kasse -o jsonpath='{.items[0].metadata.name}')
kubectl -n laden debug $K --copy-to=kasse-debug --container=kasse -- sleep 3600
kubectl -n laden wait --for=condition=Ready pod/kasse-debug --timeout=60s
kubectl -n laden exec kasse-debug -- sh -c 'ls -d /daten; mkdir /daten && echo bons=12 >> /daten/abschluss.log && cat /daten/abschluss.log'
kubectl -n laden get pod kasse-debug --show-labels

Expected:

pod/kasse-debug condition met
ls: /daten: No such file or directory
bons=12
NAME          READY   STATUS    RESTARTS   AGE   LABELS
kasse-debug   1/1     Running   0          2s    <none>

The copy confirms the cause: if /daten is missing, the closing fails; if the directory exists, it works. The last line is important: the copy has no labels. It is not attached to any Service and does not belong to any ReplicaSet that would replace or delete it. When you are done, you clean it up yourself. (--keep-labels would carry over the labels, and then the copy would receive real traffic.)

The fix belongs in the Deployment, not in the copy: an empty directory as a volume.

kubectl -n laden delete pod kasse-debug
kubectl -n laden patch deploy kasse --type=strategic -p '{"spec":{"template":{"spec":{"volumes":[{"name":"daten","emptyDir":{}}],"containers":[{"name":"kasse","volumeMounts":[{"name":"daten","mountPath":"/daten"}]}]}}}}'
kubectl -n laden rollout status deploy/kasse --timeout=90s

Wait a minute, then:

kubectl -n laden get pods -l app=kasse
stern -n laden kasse --since 40s --no-follow --include tagesabschluss 2>/dev/null

Expected:

NAME                    READY   STATUS    RESTARTS   AGE
kasse-74bbfbb76-jkxr7   1/1     Running   0          47s
kasse-74bbfbb76-xj8gl   1/1     Running   0          49s
kasse-74bbfbb76-jkxr7 kasse 2026-11-24T13:15:01+00:00 INFO tagesabschluss nach /daten/abschluss.log
kasse-74bbfbb76-xj8gl kasse 2026-11-24T13:14:59+00:00 INFO tagesabschluss nach /daten/abschluss.log

No ERROR, no restarts.

Save your progress? Sign up for free

Drill 6: Onto the Node

Sometimes the answer is not in the Pod but on the node: which containers the runtime knows, how full the disk is. kubectl debug node/… starts a Pod on exactly this node, with the node’s file system under /host. With chroot /host, you work as if you were there via SSH.

Interactively: kubectl debug node/<node> -it --image=busybox:1.37.0 --profile=sysadmin, then chroot /host. Here, too, you pass the commands directly and read the result from the log of the debug Pod. First, the name and disk of a node:

kubectl debug node/werkzeuge-worker -i --image=busybox:1.37.0 --profile=sysadmin -- \
  chroot /host sh -c 'hostname; df -h /var | tail -1'

Expected (after kubectl’s notice lines):

Creating debugging pod node-debugger-werkzeuge-worker-6l9cl with container debugger on node werkzeuge-worker.
werkzeuge-worker
/dev/sda1        77G   16G   62G  21% /var

Then the checkout containers on the node where a checkout Pod runs:

N=$(kubectl -n laden get pods -l app=kasse -o jsonpath='{.items[0].spec.nodeName}')
kubectl debug node/$N -i --image=busybox:1.37.0 --profile=sysadmin -- chroot /host crictl ps -a --name kasse
kubectl logs $(kubectl get pods -o name | grep node-debugger-$N)

Expected (IDs will differ, columns shortened):

CONTAINER           IMAGE               CREATED             STATE               NAME                ATTEMPT
3136642fd81c7       30ecbe1509090       22 seconds ago      Running             kasse               0
51508879a2545       30ecbe1509090       53 seconds ago      Exited              kasse               4

This output dates from before the fix; the running container with ATTEMPT 0 is the copy kasse-debug from Drill 5. The line Exited … 4 is the dead predecessor from Drill 3: exactly one terminated container per Pod container, the kubelet keeps no more. Older attempts have disappeared along with their logs.

After finishing, the debug Pod stays as Completed in the namespace default:

kubectl get pods -o name | grep node-debugger | xargs -r kubectl delete

Caution: --profile=sysadmin starts the Pod privileged. With chroot /host, you are root on the node. Whoever may run kubectl debug node/… owns the node. In production, this permission belongs only in emergency roles.

Save your progress? Sign up for free

Exercise: Filter Drills

Answer each question with one stern call:

  1. All lines with WARN from both checkout Pods of the last two minutes, without the +/- lines.
  2. The last two lines of each checkout in the format Pod | message, without container names.
  3. The last line of each container with tier=backend, except debug containers.

Solution

stern -n laden kasse --since 2m --no-follow --include WARN --only-log-lines
stern -n laden kasse --tail 2 --no-follow --template '{{.PodName}} | {{.Message}}{{"\n"}}' 2>/dev/null
stern -n laden -l tier=backend --tail 1 --no-follow -E debugger 2>/dev/null

Expected for the second call (values will differ):

kasse-74bbfbb76-jkxr7 | 2026-11-24T13:15:29+00:00 INFO bon=26 summe=182 EUR
kasse-74bbfbb76-jkxr7 | 2026-11-24T13:15:31+00:00 INFO bon=27 summe=189 EUR
kasse-74bbfbb76-xj8gl | 2026-11-24T13:15:29+00:00 INFO bon=27 summe=189 EUR
kasse-74bbfbb76-xj8gl | 2026-11-24T13:15:31+00:00 INFO bon=28 summe=196 EUR

The template is a Go template. The fields are named as in the JSON output (-o json):

stern -n laden kasse --tail 1 --no-follow -o json 2>/dev/null | head -1

Expected:

{"message":"2026-11-24T13:15:31+00:00 INFO bon=28 summe=196 EUR","nodeName":"werkzeuge-worker","namespace":"laden","podName":"kasse-74bbfbb76-xj8gl","containerName":"kasse","labels":{"app":"kasse","pod-template-hash":"74bbfbb76","tier":"backend"},"annotations":null}

--only-log-lines in the first call suppresses the +/- lines without redirecting stderr.

Save your progress? Sign up for free

Challenge

A colleague reports: “The checkout restarted last night after the end-of-day closing, and the logs are gone.” For any checkout Pod, find out without logs when the last container ended, with which exit code and how often it has already been restarted, with a single command. Reproduce the case by removing the volume again (kubectl -n laden rollout undo deploy/kasse).

Solution

kubectl -n laden rollout undo deploy/kasse
sleep 90
kubectl -n laden get pods -l app=kasse -o custom-columns='POD:.metadata.name,NEUSTARTS:.status.containerStatuses[0].restartCount,EXIT:.status.containerStatuses[0].lastState.terminated.exitCode,ENDE:.status.containerStatuses[0].lastState.terminated.finishedAt'

Expected (names and times will differ):

Warning: resource deployments/kasse was previously managed with 'kubectl apply'. Rolling back will not update the kubectl.kubernetes.io/last-applied-configuration annotation, which may cause unexpected behavior on future 'kubectl apply' operations. Consider using 'kubectl apply' with your previous configuration file instead.
deployment.apps/kasse rolled back
POD                     NEUSTARTS   EXIT   ENDE
kasse-bccf54c45-tpd9q   2           3      2026-11-24T13:17:51Z
kasse-bccf54c45-vs826   2           3      2026-11-24T13:17:49Z

The warning is a reminder of Day 2: kasse.yaml and the cluster have diverged since you fixed things via patch. Whoever rolls out the Deployment with kubectl apply -f kasse.yaml in the future brings the bug back. So the fix also belongs in the file.

Exit code 3 is the one from the script (exit 3). This information is in the Pod status, not in the logs, and stays as long as the Pod exists. Finally, restore the fix:

kubectl -n laden rollout undo deploy/kasse
kubectl -n laden rollout status deploy/kasse --timeout=90s

Save your progress? Sign up for free

Checkpoint

stern --version | head -1
kubectl -n laden get deploy kasse -o jsonpath='{.spec.template.spec.volumes[0].name}{"\n"}'
kubectl -n laden get pods --no-headers | grep -c kasse
kubectl get pods -o name | grep -c node-debugger

Expected (the last line is 0, and grep -c exits with exit code 1):

version: 1.35.0
daten
2
0

Interview Note

  • Pod in CrashLoopBackOff, how do you proceed? kubectl describe (exit code, reason, events), then kubectl logs or --previous depending on the state, then a copy with kubectl debug --copy-to and a different command if the container dies too quickly.
  • How do you debug distroless images? An ephemeral container with --target, processes and file system via /proc/1/…. No restart, no new image needed.
  • Why is kubectl debug security-relevant? Ephemeral containers see the target’s environment and files; node debugging is root on the node. Both need dedicated, narrowly granted permissions.

Enterprise Note

  • stern is for the moment, not for the archive. Logs that should survive a night belong in a central collection (Fluent Bit or Alloy into Loki or OpenSearch). The kubelet keeps only one dead container, and the log files rotate by size.
  • Ephemeral containers show up in audit logs as patch on pods/ephemeralcontainers. An alert on this in production shows who looked into which Pod and when.
  • For teams, a fixed debug image (busybox is often enough, netshoot for networking, see Day 8) from your own registry is worth it, instead of pulling an arbitrary image from the internet every time.

Contents

More