Skip to content
LF Cert Trainer

Lesson 44 · Section 4: Logging & Monitoring

Lesson 44: Managing application logs: kubectl logs and what happens behind it

Where a container's output goes on the node, how kubectl logs fetches it, how to read logs from crashed, multi-container and replicated Pods, and why rotation and Pod deletion make logs disappear. · 20 min read · 4 min video

1/10Managing application logs
0:00 / 4:12

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

Why application logs need their own lesson

On a single server you know where the logs are: one machine, one file, and tail -f does the rest. In a cluster that picture falls apart:

  • The scheduler picks the node, so you do not know which machine holds the output.
  • A container's filesystem is thrown away when the container is replaced, and the files written inside go with it.
  • One Pod can run several containers, and one application usually runs as several Pods.

Kubernetes answers this with one convention and one command. The convention: an application prints its log lines to standard output and standard error, and nothing more. The command: kubectl logs, which finds the right node and the right container and brings the lines to your terminal.

This lesson is about the logs of your applications. Monitoring the cluster's own components is the subject of the previous lesson; the two meet at the end, because the control plane components of a kubeadm cluster are Pods too, and the same commands read their logs.

What a container log is

From a line of output to your terminalThe Pod's nodeprintsappendsasksforwardsreadsYoukubectl logs webAPI serverpods/logkubeletport 10250App containerstdout and stderrcontainerdcaptures both streamsLog file/var/log/pods/...
From a line of output to your terminal. The application only prints. The runtime writes the file, and kubectl logs is a request that the API server passes on to the kubelet of the node that holds the file.

Parts:

  • You (kubectl logs web)
  • API server (pods/log)
  • kubelet (port 10250), in The Pod's node
  • App container (stdout and stderr), in The Pod's node
  • containerd (captures both streams), in The Pod's node
  • Log file (/var/log/pods/...), in The Pod's node

Connections:

  • App container to containerd: prints
  • containerd to Log file: appends
  • You to API server: asks
  • API server to kubelet: forwards
  • kubelet to Log file: reads

Four parts are involved, and each one does very little:

PartWhat it does with logs
The applicationPrints lines to stdout (normal output) and stderr (errors). It does not open files, rotate anything or know about Kubernetes
The container runtime (containerd, CRI-O)Captures both streams and appends each line to a file on the node, in the standard CRI logging format
The kubeletTells the runtime where to write, rotates the files, deletes them with the Pod, and serves them on request through its port 10250
The API serverExposes the log subresource of a Pod and forwards each request to the kubelet of the Pod's node

This is why well-built container images log to the console. The official nginx image, for example, makes /var/log/nginx/access.log a symbolic link to /dev/stdout and error.log a link to /dev/stderr, so a program that only knows how to write files still ends up in kubectl logs.

How it works

The files on the node

The kubelet gives every container its own folder under /var/log/pods, and the runtime writes one file per container instance there. The number in the file name is the container's restart count:

/var/log/pods/<namespace>_<pod-name>_<pod-uid>/<container-name>/<restart-count>.log

/var/log/pods/default_web_0b1f6c1e-52a7-4f0e-9d53-8a1a6f4f7c11/app/0.log
/var/log/pods/default_web_0b1f6c1e-52a7-4f0e-9d53-8a1a6f4f7c11/app/1.log      (after one restart)

A second folder, /var/log/containers, holds symbolic links to the same files with flatter names (<pod>_<namespace>_<container>-<container-id>.log). Logging agents usually read that one.

Each line in the file has four fields: a timestamp, the stream, a tag, and the text the application printed.

2026-11-30T10:15:02.401553017Z stdout F GET /healthz 200
2026-11-30T10:15:03.118220450Z stderr F upstream timed out

The tag is F for a full line and P for a part of a very long line that the runtime had to split. kubectl logs strips the first three fields and prints only the text, with both streams mixed in the order they were written. The --timestamps flag puts the first field back.

What kubectl logs really does

  1. kubectl asks the API server for pods/web/log
  2. API server checks you may get pods/log
  3. API server calls the kubelet on the Pod's node
  4. kubelet reads the newest file of that container
  5. Lines stream back through the API server
One kubectl logs request

Three practical consequences follow from this path:

  • The API server must reach the kubelet. If the node is NotReady or a firewall blocks port 10250, kubectl get pods still works (it only reads etcd through the API server) but kubectl logs hangs or fails with a connection error.
  • You need permission on pods/log, a separate subresource. A Role that grants get on pods alone lets you list Pods but not read their logs.
  • There is no log storage in the control plane. Nothing is copied to etcd. The only copy is the file on the node.

Rotation and lifetime

Which file each command readsContainer's log foldernewest fileone backevery filekubectl logscurrent instancekubectl logs -pinstance before itLogging agentDaemonSet on the node1.logbeing written now0.logbefore the restart1.log.20261130rotated at 10Mi
Which file each command reads. One folder per container, one file per container instance. kubectl logs reads only the newest file of the current instance; a logging agent on the node can read them all.

Parts:

  • kubectl logs (current instance)
  • kubectl logs -p (instance before it)
  • Logging agent (DaemonSet on the node)
  • 1.log (being written now), in Container's log folder
  • 0.log (before the restart), in Container's log folder
  • 1.log.20261130 (rotated at 10Mi), in Container's log folder

Connections:

  • kubectl logs to 1.log: newest file
  • kubectl logs -p to 0.log: one back
  • Logging agent to 1.log.20261130: every file

Log files would fill the node's disk if nobody cleaned up, so the kubelet rotates them. Two settings in the kubelet's configuration file (/var/lib/kubelet/config.yaml) control it:

SettingDefaultMeaning
containerLogMaxSize10MiA log file is rotated when it reaches this size
containerLogMaxFiles5How many log files are kept per container; the oldest is deleted

What this means for you:

  • kubectl logs reads only the newest file. If a container has written 40 MiB with the default settings, kubectl logs returns at most the last 10 MiB. Older lines are still on the node in rotated files, until the fifth file pushes them out.
  • One previous instance is kept. When a container restarts, the kubelet keeps the terminated container and its log, which is what kubectl logs --previous reads. The instance before that is gone.
  • Deleting the Pod deletes its logs. The folder under /var/log/pods is removed with the Pod. The same happens when a Pod is evicted, and when a Deployment replaces its Pods during a rollout.
Under the hood · Termination messages, split streams and node-level details
  • Termination message. Besides the log, a container can leave a short final message in the file /dev/termination-log; it shows up under Last State in kubectl describe pod. Most applications never write it. Setting terminationMessagePolicy: FallbackToLogsOnError on the container makes the kubelet use the end of the log instead (the last 2048 bytes or 80 lines, whichever is smaller) when the container exits with an error, so the reason for a crash appears directly in describe.
  • stdout and stderr together. kubectl logs prints both streams interleaved. Fetching only one of them through the API is an alpha feature (the PodLogsQuerySplitStreams feature gate, off by default), so do not count on it.
  • Rotated files. The kubelet renames a full file by adding a timestamp and compresses older ones with gzip. It checks sizes every 10 seconds by default (containerLogMonitorInterval), so a very chatty container can overshoot the size limit a little.
  • Node-pressure eviction. Logs count towards a Pod's use of local ephemeral storage. A container that logs without limit can get its Pod evicted when the node runs low on disk, or when the Pod exceeds its own ephemeral-storage limit.
  • Logs of system services. The kubelet and the container runtime are not containers. They are systemd services, and their logs are in the journal: journalctl -u kubelet, journalctl -u containerd.

The flags worth knowing

You wantCommand
Everything the container wrote (newest file)kubectl logs web
A Pod in another namespacekubectl logs web -n shop
Keep the stream openkubectl logs web -f
Only the last 20 lineskubectl logs web --tail=20
Only the last 5 minuteskubectl logs web --since=5m
Lines after a point in timekubectl logs web --since-time=2026-11-30T10:00:00Z
When each line was writtenkubectl logs web --timestamps
The container that ran before the last restartkubectl logs web --previous (short: -p)
One container of a multi-container Podkubectl logs web -c log-shipper
Every container of the Podkubectl logs web --all-containers
Every Pod with a labelkubectl logs -l app=web --prefix
A Pod of a Deployment, Job or StatefulSetkubectl logs deploy/web, kubectl logs job/backup

Which container, which Pod

A Pod with one container needs no -c. With several containers, kubectl does not fail any more as it did in old versions: it picks a default and tells you so on stderr.

$ kubectl logs web
Defaulted container "app" out of: app, log-shipper, init-config (init)

The default is the container named in the Pod's kubectl.kubernetes.io/default-container annotation, or else the first container in the spec. That is often not the one you wanted, so in a multi-container Pod always pass -c. Init containers are read the same way: kubectl logs web -c init-config.

Reading several Pods at once has its own rules:

FormWhat you get
kubectl logs deploy/webThe logs of one Pod of the Deployment, chosen by kubectl (Found 3 pods, using pod/web-...)
kubectl logs -l app=webAll matching Pods, but only the last 10 lines of each unless you set --tail
kubectl logs -l app=web -fA live stream of up to 5 Pods; raise it with --max-log-requests
kubectl logs -l app=web --prefixThe same, with [pod/name/container] in front of every line

When the application does not log to stdout

When the application writes to a file insteadOne PodwritestailsstdoutreadsshipsApp containerwrites app.logShared volumeemptyDirSidecartail -F to stdoutNode log file/var/log/pods/...Logging agentDaemonSetLog backendsearch and retention
When the application writes to a file instead. A streaming sidecar turns a log file into a normal output stream, so kubectl logs and the node's logging agent see it like any other container log.

Parts:

  • App container (writes app.log), in One Pod
  • Shared volume (emptyDir), in One Pod
  • Sidecar (tail -F to stdout), in One Pod
  • Node log file (/var/log/pods/...)
  • Logging agent (DaemonSet)
  • Log backend (search and retention)

Connections:

  • App container to Shared volume: writes
  • Sidecar to Shared volume: tails
  • Sidecar to Node log file: stdout
  • Node log file to Logging agent: reads
  • Logging agent to Log backend: ships

Some applications insist on writing to a file inside the container. Then kubectl logs is empty, and the file disappears with every restart. There are three ways out, from quickest to most complete:

ApproachHowUse it when
Read the file in placekubectl exec web -- tail -n 50 /var/log/app/app.logYou need a quick look and the container is running and has tail
Streaming sidecarPut the file on a shared emptyDir; a second container runs tail -F on itYou want the file in kubectl logs and in the node's log files
Node logging agentA DaemonSet (Fluent Bit, Fluentd, Vector and others) reads /var/log/pods on every node and ships it to a backendYou need history, search, and logs of deleted Pods

Kubernetes itself ships no cluster-wide log storage. The node agent pattern is what almost every real cluster adds, and it works without touching the applications, because everything already lands in /var/log/pods. The streaming sidecar exists to bring file-writing applications into that same path.

Using it

Example · Find out why a Pod is crash looping

The Pod api in namespace shop shows CrashLoopBackOff. Work from the status to the output of the container that died.

kubectl get pod api -n shop
# NAME   READY   STATUS             RESTARTS      AGE
# api    0/1     CrashLoopBackOff   4 (20s ago)   2m

kubectl logs api -n shop                 # often empty: the new container has only just started
kubectl logs api -n shop --previous
# starting api v2.3
# FATAL: environment variable DB_HOST is not set

kubectl describe pod api -n shop | grep -A6 "Last State"
#   Last State:     Terminated
#     Reason:       Error
#     Exit Code:    1

The log names the cause: a missing environment variable. If --previous answers previous terminated container "api" in pod "api" not found, the container has not restarted yet, and plain kubectl logs is the right command. If the exit code is 137 with reason OOMKilled, the kernel killed the container: the log simply stops, and the answer is in describe, not in the log.

Example · Read one container of a multi-container Pod and save the errors

The Pod web runs the containers app and log-shipper. Save every line of app that contains ERROR to /opt/web-errors.txt.

kubectl get pod web -o jsonpath='{.spec.containers[*].name}{"\n"}'
# app log-shipper

kubectl logs web -c app | grep ERROR > /opt/web-errors.txt
cat /opt/web-errors.txt
# 2026/11/30 10:15:44 ERROR payment service: connection refused

Listing the container names first costs five seconds and avoids reading the wrong one. kubectl describe pod web shows the same names if you prefer it to JSONPath.

Example · Make a file-writing application visible to kubectl logs

The application writes to /var/log/app/app.log and prints nothing. Add a sidecar that streams the file.

apiVersion: v1
kind: Pod
metadata:
  name: legacy
spec:
  containers:
    - name: app
      image: busybox:1.37
      command: ["sh", "-c", "while true; do echo \"$(date) INFO working\" >> /var/log/app/app.log; sleep 5; done"]
      volumeMounts:
        - name: logs
          mountPath: /var/log/app
    - name: log-stream
      image: busybox:1.37
      command: ["sh", "-c", "tail -n+1 -F /var/log/app/app.log"]
      volumeMounts:
        - name: logs
          mountPath: /var/log/app
  volumes:
    - name: logs
      emptyDir: {}
kubectl apply -f legacy.yaml
kubectl logs legacy -c app             # empty: the application prints nothing
kubectl logs legacy -c log-stream      # Mon Nov 30 10:20:05 UTC 2026 INFO working

tail -F (capital F) keeps following the file by name, so it survives the application rotating or recreating it; -n+1 starts from the first line instead of the last ten. You cannot add a container to a running Pod: delete and recreate the Pod, or change the Pod template of its Deployment.

Example · Read logs when kubectl cannot

The API server is down, so every kubectl command fails. Its own log is still on the control plane node, because it is a container like any other.

ssh controlplane
sudo crictl ps -a | grep kube-apiserver          # -a also lists exited containers
# 3f1c9a7b2d1e   ...   Exited   kube-apiserver   6   ...

sudo crictl logs --tail=20 3f1c9a7b2d1e
# Error: unknown flag: --etcd-server

# the same lines, straight from the files:
sudo ls /var/log/pods/ | grep kube-apiserver
sudo tail -n 20 /var/log/pods/kube-system_kube-apiserver-controlplane_*/kube-apiserver/*.log

# the kubelet is not a container:
sudo journalctl -u kubelet --no-pager | tail -n 20

The same route works for any Pod on a node whose kubelet has lost contact with the control plane.

Tricks

Common mistakes

  • Reading the wrong container. In a multi-container Pod, kubectl silently defaults to one container and prints a short Defaulted container note. Pass -c every time.
  • Expecting logs from a Pod that never started. Pending, ContainerCreating and ImagePullBackOff Pods have no logs; kubectl answers that the container is waiting to start. Use kubectl describe pod and read the events.
  • Looking for logs after deleting the Pod. They are gone from the node. The replacement Pod has a new name and starts with an empty log.
  • Forgetting the namespace. kubectl logs web in the wrong namespace says pods "web" not found. Add -n, or find the Pod with kubectl get pods -A | grep web.
  • Trusting kubectl logs deploy/web to show everything. It shows one Pod. The failing replica may be another one; use the label selector.
  • Assuming the full history is there. After rotation, only the newest file is returned, and after a second restart the older instance is lost. Logs you must keep belong in a logging backend.
  • Expecting application files in kubectl logs. Only stdout and stderr are captured. A file inside the container needs kubectl exec, a streaming sidecar or a change to the application.

Recap

  • Kubernetes collects only stdout and stderr. The runtime writes them to /var/log/pods/... on the node, and kubectl logs asks that node's kubelet to read the file.
  • -c picks the container, --previous reads the instance that crashed, -f, --tail and --since shape the output, and -l with --prefix reads many Pods.
  • No logs yet means no container ran: read the events with kubectl describe pod.
  • Logs are not kept: rotation at 10Mi (5 files), one previous instance, and everything is deleted with the Pod.
  • Without a working API server, read the same files on the node with crictl logs; the kubelet's own log is in journalctl -u kubelet.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Practise: try it on a real cluster

A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.

  • Use kubectl logs on a multi-container pod, a crashed container and a set of replicas to find what fails and why.

    Investigate · Level 2 · standard · target 12 min

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.