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
Official competencies this lesson covers
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
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:
| Part | What it does with logs |
|---|---|
| The application | Prints 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 kubelet | Tells the runtime where to write, rotates the files, deletes them with the Pod, and serves them on request through its port 10250 |
| The API server | Exposes 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
- kubectl asks the API server for pods/web/log
- API server checks you may get pods/log
- API server calls the kubelet on the Pod's node
- kubelet reads the newest file of that container
- Lines stream back through the API server
Three practical consequences follow from this path:
- The API server must reach the kubelet. If the node is
NotReadyor a firewall blocks port 10250,kubectl get podsstill works (it only reads etcd through the API server) butkubectl logshangs or fails with a connection error. - You need permission on
pods/log, a separate subresource. A Role that grantsgetonpodsalone 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
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:
| Setting | Default | Meaning |
|---|---|---|
containerLogMaxSize | 10Mi | A log file is rotated when it reaches this size |
containerLogMaxFiles | 5 | How many log files are kept per container; the oldest is deleted |
What this means for you:
kubectl logsreads only the newest file. If a container has written 40 MiB with the default settings,kubectl logsreturns 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 --previousreads. The instance before that is gone. - Deleting the Pod deletes its logs. The folder under
/var/log/podsis 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 underLast Stateinkubectl describe pod. Most applications never write it. SettingterminationMessagePolicy: FallbackToLogsOnErroron 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 indescribe. - stdout and stderr together.
kubectl logsprints both streams interleaved. Fetching only one of them through the API is an alpha feature (thePodLogsQuerySplitStreamsfeature 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-storagelimit. - 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 want | Command |
|---|---|
| Everything the container wrote (newest file) | kubectl logs web |
| A Pod in another namespace | kubectl logs web -n shop |
| Keep the stream open | kubectl logs web -f |
| Only the last 20 lines | kubectl logs web --tail=20 |
| Only the last 5 minutes | kubectl logs web --since=5m |
| Lines after a point in time | kubectl logs web --since-time=2026-11-30T10:00:00Z |
| When each line was written | kubectl logs web --timestamps |
| The container that ran before the last restart | kubectl logs web --previous (short: -p) |
| One container of a multi-container Pod | kubectl logs web -c log-shipper |
| Every container of the Pod | kubectl logs web --all-containers |
| Every Pod with a label | kubectl logs -l app=web --prefix |
| A Pod of a Deployment, Job or StatefulSet | kubectl 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:
| Form | What you get |
|---|---|
kubectl logs deploy/web | The logs of one Pod of the Deployment, chosen by kubectl (Found 3 pods, using pod/web-...) |
kubectl logs -l app=web | All matching Pods, but only the last 10 lines of each unless you set --tail |
kubectl logs -l app=web -f | A live stream of up to 5 Pods; raise it with --max-log-requests |
kubectl logs -l app=web --prefix | The same, with [pod/name/container] in front of every line |
When the application does not log to stdout
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:
| Approach | How | Use it when |
|---|---|---|
| Read the file in place | kubectl exec web -- tail -n 50 /var/log/app/app.log | You need a quick look and the container is running and has tail |
| Streaming sidecar | Put the file on a shared emptyDir; a second container runs tail -F on it | You want the file in kubectl logs and in the node's log files |
| Node logging agent | A DaemonSet (Fluent Bit, Fluentd, Vector and others) reads /var/log/pods on every node and ships it to a backend | You 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 containernote. Pass-cevery time. - Expecting logs from a Pod that never started.
Pending,ContainerCreatingandImagePullBackOffPods have no logs; kubectl answers that the containeris waiting to start. Usekubectl describe podand 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 webin the wrong namespace sayspods "web" not found. Add-n, or find the Pod withkubectl get pods -A | grep web. - Trusting
kubectl logs deploy/webto 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 needskubectl 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, andkubectl logsasks that node's kubelet to read the file. -cpicks the container,--previousreads the instance that crashed,-f,--tailand--sinceshape the output, and-lwith--prefixreads 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 injournalctl -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.