Skip to content
LF Cert Trainer

Lesson 42 · Section 4: Logging & Monitoring

Lesson 42: Logging and monitoring: how you see inside a cluster

The four signals a cluster gives you (object status, events, metrics and logs), how each one travels from a container to your terminal, what Kubernetes keeps and for how long, and the order to check them in the exam. · 18 min read · 4 min video

1/12Logging and monitoring
0:00 / 4:15

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

Why you need a way to look inside

On a single server you know where to look: log in, run top, read the files in /var/log. A cluster takes that comfort away. The application runs as many containers, on nodes chosen by the scheduler, and those containers are replaced whenever they crash, are rescheduled or are rolled out again. The container that misbehaved a minute ago may no longer exist, and you may never have had a shell on its node.

So the cluster has to bring the evidence to you. This section of the course is about that evidence: monitoring answers how much is being used and is it healthy, logging answers what did the software say. This lesson is the map. The next two lessons go deeper: monitoring cluster components and resource usage, then application logs.

The four signals

Four signals, one front doorasksgeteventstoplogskubectlyou, in the examAPI serverthe only front doorObject statuswhat is true nowEventswhat just happenedMetricsCPU and memory in useLogswhat the app says
Four signals, one front door. Everything you read with kubectl comes through the API server. Status and events are stored in etcd; metrics and logs are fetched live from the nodes when you ask.

Parts:

  • kubectl (you, in the exam)
  • API server (the only front door)
  • Object status (what is true now)
  • Events (what just happened)
  • Metrics (CPU and memory in use)
  • Logs (what the app says)

Connections:

  • kubectl to API server: asks
  • API server to Object status: get
  • API server to Events: events
  • API server to Metrics: top
  • API server to Logs: logs

Everything you can learn with kubectl comes through the API server, and it comes in four kinds:

SignalAnswersRead it withProduced byKept
Object statusWhat is true right now?kubectl get, kubectl describeControllers and kubelets writing statusIn etcd, while the object exists
EventsWhat just happened to this object?kubectl describe, kubectl eventsScheduler, kubelet, controllersIn etcd, about 1 hour
MetricsHow much CPU and memory is in use?kubectl topkubelet, collected by metrics-serverLatest reading only, in memory
LogsWhat did the application say?kubectl logsThe container's own outputA file on the node, until the Pod is deleted

The first two are ordinary API objects stored in etcd. The last two are not stored in the API at all: when you ask for them, the request travels on to a node and the answer is read live. That is why kubectl get pods still works when a node is unreachable, while kubectl logs and kubectl top for the Pods on that node do not.

How metrics reach you

How CPU and memory figures reach kubectl topusageeach 15sMetrics APIreadsreadsContainerscgroup counterskubeletcAdvisor built inmetrics-serveradd-on, memory onlyAPI servermetrics.k8s.iokubectl topnodes and PodsAutoscalersHPA and VPA
How CPU and memory figures reach kubectl top. The kubelet measures, metrics-server collects, and the API server serves the result. metrics-server keeps only the latest reading, in memory.

Parts:

  • Containers (cgroup counters)
  • kubelet (cAdvisor built in)
  • metrics-server (add-on, memory only)
  • API server (metrics.k8s.io)
  • kubectl top (nodes and Pods)
  • Autoscalers (HPA and VPA)

Connections:

  • Containers to kubelet: usage
  • kubelet to metrics-server: each 15s
  • metrics-server to API server: Metrics API
  • API server to kubectl top: reads
  • API server to Autoscalers: reads

Kubernetes calls this chain the resource metrics pipeline:

  1. The Linux kernel counts CPU time and memory for every container in its cgroup.
  2. The kubelet on each node reads those counters. It has a small collector, cAdvisor, compiled in for exactly this, and serves the figures on its own HTTPS port, 10250.
  3. metrics-server, an add-on that runs as a Deployment in kube-system, asks every kubelet for its figures about every 15 seconds and keeps the latest answer in memory.
  4. metrics-server registers itself with the API server as an extra API, metrics.k8s.io (the Metrics API). The API server forwards requests for that API to it.
  5. kubectl top reads the Metrics API. So do the Horizontal and Vertical Pod Autoscalers.

Three consequences are worth knowing before you ever type kubectl top:

  • It is an add-on. kubeadm does not install metrics-server. Without it, kubectl top answers error: Metrics API not available, and an autoscaler that targets CPU cannot work.
  • There is no history. metrics-server holds one recent reading per Pod and node. It cannot tell you what memory looked like ten minutes ago, and a restart of metrics-server loses even that.
  • Only CPU and memory. No request rates, no disk, no network, nothing about your application.
kubectl top nodes
kubectl top pods -n shop --sort-by=memory
kubectl top pod web-6d9c7b5f4-x2kqp --containers

CPU is shown in millicores (250m is a quarter of one core) and memory in mebibytes (Mi), the same units you write in resource requests and limits.

Under the hood · The other pipeline: full metrics with Prometheus

The resource metrics pipeline is deliberately tiny. Real monitoring uses a second, full metrics pipeline that you install yourself, most often Prometheus:

  • Every Kubernetes component exposes a /metrics endpoint in the Prometheus text format: the API server, the scheduler, the controller manager, etcd, and the kubelet (which also serves per-container figures on /metrics/cadvisor and the compact set that metrics-server reads on /metrics/resource).
  • A monitoring system scrapes those endpoints on a schedule and stores every sample, which is what gives you history, graphs and alerts.
  • kube-state-metrics is a common companion. It turns the state of API objects into metrics (how many replicas a Deployment wants and has, which Pods are not ready). metrics-server reports usage; kube-state-metrics reports state. The names are similar and the jobs are not.
  • An adapter can publish chosen metrics back into the cluster as custom.metrics.k8s.io, so an autoscaler can scale on requests per second instead of CPU.

You can peek at the raw material without installing anything:

kubectl get --raw /metrics | head                              # the API server's own metrics
kubectl get --raw /api/v1/nodes/node-1/proxy/metrics/resource  # what metrics-server reads from one kubelet

For the CKA you are expected to use metrics-server and kubectl top, not to build a Prometheus stack.

How logs reach you

How a line of output reaches kubectl logswritessavesreadsservesstreamstailsshipsContainerstdout and stderrcontainerdcaptures both streamsLog file/var/log/pods/...API serverproxies the requestkubeletreads and rotatesLogging agentDaemonSet, not built inkubectl logsthe newest fileLog backendsearch and history
How a line of output reaches kubectl logs. The container only writes to its output streams. The runtime turns them into a file on the node, the kubelet serves that file, and anything long-term needs an agent you install yourself.

Parts:

  • Container (stdout and stderr)
  • containerd (captures both streams)
  • Log file (/var/log/pods/...)
  • API server (proxies the request)
  • kubelet (reads and rotates)
  • Logging agent (DaemonSet, not built in)
  • kubectl logs (the newest file)
  • Log backend (search and history)

Connections:

  • Container to containerd: writes
  • containerd to Log file: saves
  • Log file to kubelet: reads
  • kubelet to API server: serves
  • API server to kubectl logs: streams
  • Log file to Logging agent: tails
  • Logging agent to Log backend: ships

Kubernetes has one rule for application logs: write to standard output and standard error. The application does not need to know about log files, and the cluster does not need to know about the application.

  1. The container writes lines to stdout and stderr.
  2. The container runtime (containerd on most clusters) captures both streams and appends them to a file on the node, one line per entry with a timestamp and the stream name in front.
  3. The file lives under /var/log/pods/, in a folder named after the namespace, the Pod name and the Pod UID, with one subfolder per container. /var/log/containers/ holds symlinks to the same files with friendlier names.
  4. kubectl logs asks the API server, the API server asks the kubelet on that node, and the kubelet reads the file and streams it back.
/var/log/pods/shop_web-6d9c7b5f4-x2kqp_0c1d.../web/0.log
2026-11-30T10:14:02.118204817Z stdout F GET /healthz 200
2026-11-30T10:14:07.530991204Z stderr F Error: DATABASE_URL is not set

The number in the file name is the container's restart count: 0.log is the first run, 1.log the run after the first restart.

What happens to the files

The kubelet looks after the files. It rotates a container's log when it reaches containerLogMaxSize (default 10Mi) and keeps at most containerLogMaxFiles (default 5) per container. Both are fields in the kubelet configuration file.

When this happensThe logs
The container restartsThe new run starts a new file. The previous run is kept, and kubectl logs --previous reads it
The file reaches 10MiIt is rotated. kubectl logs reads the newest file, so very old lines drop out of view
The Pod is deleted or evictedIts folder is removed. The logs are gone
The node is lostEverything on its disk is lost with it

Logs of the cluster itself

The cluster's own components log in two different places, and it depends on how each one runs:

ComponentRuns asRead its logs with
kubeletsystemd service on every nodejournalctl -u kubelet
containerdsystemd service on every nodejournalctl -u containerd
kube-apiserver, etcd, kube-scheduler, kube-controller-managerStatic Pods on kubeadm clusterskubectl -n kube-system logs <pod>, or crictl logs on the node
kube-proxy, CoreDNS, the network pluginOrdinary Pods in kube-systemkubectl -n kube-system logs <pod>

The kubelet cannot run as a Pod, because it is the thing that starts Pods. So when a node is NotReady or static Pods do not come up, the journal is where the explanation is.

Keeping logs for longer

Kubernetes has no built-in cluster-level logging. To keep logs after a Pod is gone, or to search across Pods, you add one of three patterns:

PatternHow it worksGood for
Node logging agentA DaemonSet (Fluent Bit, Fluentd, Vector and others) mounts /var/log on every node, tails the files and ships them to a backendThe default choice: nothing changes in the applications
Sidecar containerA second container in the Pod reads a log file from a shared volume and prints it to its own stdout, or ships it directlyApplications that insist on writing to files
Direct pushThe application sends its logs to the backend itselfRare; ties the application to the backend

The sidecar pattern returns later in this course with multi-container Pods. For now, remember which problem each one solves.

Events: the log of the cluster's decisions

Events are small API objects that components write when something happens to an object: the scheduler assigned a Pod, the kubelet pulled an image, a probe failed, a volume could not be mounted. They are the quickest route from "it does not work" to "why".

kubectl describe pod web-6d9c7b5f4-x2kqp          # events for one object, at the bottom
kubectl events --for pod/web-6d9c7b5f4-x2kqp      # the same, as a list
kubectl events -A --types=Warning                 # everything that went wrong, cluster-wide
kubectl get events --sort-by=.lastTimestamp       # the classic form, oldest first

Events are not application logs: your application's output never appears there. And they expire. The API server deletes each event after its --event-ttl, one hour by default, so kubectl describe on something that broke yesterday shows an empty list.

What you get, and what you add

NeedBuilt inAdd-on
Current state of every objectkubectl get, kubectl describe
Recent decisions and failuresEvents, for about an hourAn event exporter, to keep them
Current CPU and memoryThe kubelet measures itmetrics-server, to read it with kubectl top
Usage over time, alerts, dashboardsPrometheus and Grafana, or a hosted service
Logs of existing containerskubectl logs
Logs after a Pod is gone, search across PodsA logging agent and a backend (Loki, Elasticsearch, OpenSearch)
Component healthkubectl get nodes, the API server's /readyz and /livez

Using it

Example · The first five minutes with a failing application

The Deployment web in namespace shop is reported as down. Read the four signals in order, cheapest first.

kubectl -n shop get pods -o wide                       # 1. status: which Pods, which state, how many restarts
kubectl -n shop describe pod web-6d9c7b5f4-x2kqp       # 2. events: the reason, at the bottom
kubectl -n shop logs web-6d9c7b5f4-x2kqp               # 3. logs: what the application said
kubectl -n shop logs web-6d9c7b5f4-x2kqp --previous    #    ...and what the run before this one said
kubectl -n shop top pod web-6d9c7b5f4-x2kqp            # 4. metrics: is it near its limits?

How to read what comes back:

You seeIt usually meansLook next at
Pending, event FailedSchedulingNo node fitsThe event text: taints, requests, selectors
ImagePullBackOffWrong image name or missing credentialsThe event text; logs will be empty
CrashLoopBackOffThe container starts and exitskubectl logs --previous
Running but 0/1 readyThe readiness probe failsEvents (Unhealthy), then logs
OOMKilled in the last stateMemory limit reachedkubectl top pod, then the limit

Example · Check whether metrics work, and find the heaviest Pod

First find out whether the Metrics API is there at all:

kubectl top nodes
kubectl -n kube-system get deployment metrics-server
kubectl get apiservices | grep metrics.k8s.io          # AVAILABLE must be True

error: Metrics API not available with no Deployment means metrics-server is not installed. A Deployment that exists while the APIService shows False means metrics-server runs but cannot do its job; read its logs with kubectl -n kube-system logs deployment/metrics-server.

When it works, a typical exam task is one line:

kubectl top pods -A --sort-by=cpu --no-headers | head -n 1
kubectl top pods -n shop -l app=web --sort-by=memory
kubectl top pod web-6d9c7b5f4-x2kqp -n shop --containers

If the task says "write the name of the Pod to a file", cut the column instead of typing it:

kubectl top pods -n shop --sort-by=cpu --no-headers | head -n 1 | awk '{print $1}' > /opt/answers/high-cpu.txt

Example · Read logs on the node when kubectl cannot

kubectl answers The connection to the server ... was refused. The API server is down, so every signal that travels through it is gone too. Go to the control plane node and read the evidence where it is produced:

ssh controlplane
sudo systemctl status kubelet                          # is the kubelet itself running?
sudo journalctl -u kubelet --since "10 min ago" --no-pager | tail -n 30
sudo crictl ps -a | grep -E "kube-apiserver|etcd"      # did the containers start, did they exit?
sudo crictl logs <container-id>                        # the same output kubectl logs would show
sudo ls /var/log/pods/                                 # one folder per Pod, with the log files inside
sudo tail -n 20 /var/log/pods/kube-system_kube-apiserver-*/kube-apiserver/*.log

Read them from the outside in: the kubelet's journal tells you whether it could start the container, and the container's own log tells you why it exited.

Tricks

Common mistakes

  • Expecting kubectl top to work everywhere. It needs metrics-server. On a fresh kubeadm cluster it is not there, and for the first seconds after a Pod starts there is no reading for it yet.
  • Deleting the Pod to "fix" it before reading its logs. The logs are deleted with the Pod. Read first, restart second.
  • Looking for application output in events, or for scheduling decisions in logs. Events are written by Kubernetes components about objects. Logs are written by the container. They never mix.
  • Forgetting that logs and metrics need the node. If a node is NotReady, kubectl logs for its Pods times out even though kubectl get still shows them. Status comes from etcd; logs come from the kubelet.
  • Searching /var/log for the kubelet's log file. On systemd nodes the kubelet and the container runtime log to the journal. Use journalctl -u kubelet.
  • Writing application logs to a file inside the container. kubectl logs only shows stdout and stderr. A file inside the container is invisible to it and disappears with the container, unless a sidecar or a volume takes care of it.
  • Confusing metrics-server with a monitoring system. It has one reading, no history and no alerts. It exists so that kubectl top and the autoscalers have something to read.

Recap

  • A cluster gives you four signals through the API server: status, events, metrics and logs. Read them in that order.
  • Status and events are stored in etcd; events for about one hour. Metrics and logs are fetched live from the node.
  • Metrics travel kernel, kubelet, metrics-server, Metrics API, kubectl top. metrics-server is an add-on with no history.
  • Logs travel stdout/stderr, container runtime, a file under /var/log/pods, kubelet, kubectl logs. They are rotated at 10Mi and deleted with the Pod.
  • The kubelet and the container runtime log to the journal; everything that runs as a Pod logs like a Pod.
  • History, dashboards, alerts and searchable logs are add-ons: Prometheus for metrics, a node logging agent for logs.

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.

Discussion

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