Skip to content
LF Cert Trainer

Lesson 43 · Section 4: Logging & Monitoring

Lesson 43: Monitor cluster components: Metrics Server and kubectl top

Where CPU and memory numbers come from in Kubernetes, how Metrics Server collects them from every kubelet, how to read them with kubectl top, and how to check that the cluster's own components are healthy. · 20 min read · 5 min video

1/12Monitor cluster components
0:00 / 4:53

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

Why you need to monitor a cluster

A cluster can accept your YAML and still be in trouble. A node may be at 98% memory, one Pod may be eating a whole CPU, or the controller manager may have been restarting all night. None of that shows in kubectl get pods until something finally breaks. Monitoring means collecting numbers about the cluster so you can answer four questions:

QuestionWhere the answer comes from
How full are the nodes?kubectl top nodes (needs Metrics Server)
Which Pods and containers use the most CPU and memory?kubectl top pods (needs Metrics Server)
Are the cluster's own components up?The API server's health endpoints, the Pods in kube-system, node conditions
What happened an hour ago, and who gets woken up?A monitoring system such as Prometheus. Kubernetes does not ship one

Kubernetes deliberately does not include a full monitoring system. It gives you the raw numbers on every node and one small, optional add-on, Metrics Server, that makes the current CPU and memory use available through the Kubernetes API. That add-on is what the CKA exam expects you to use.

How the numbers travel

Where the numbers in kubectl top come fromasksasksforwardsscrapes every 15sasksreadskubectl topyouAPI servermetrics.k8s.iometrics-serverlatest values, in RAMHPA and VPAautoscalerskubelet/metrics/resourceContainerscgroup counterscAdvisorinside the kubelet
Where the numbers in kubectl top come from. Every node measures its own containers. Metrics Server collects those numbers from each kubelet and serves the latest ones through the API server, so kubectl and the autoscalers never talk to a node.

Parts:

  • kubectl top (you)
  • API server (metrics.k8s.io)
  • metrics-server (latest values, in RAM)
  • HPA and VPA (autoscalers)
  • kubelet (/metrics/resource)
  • Containers (cgroup counters)
  • cAdvisor (inside the kubelet)

Connections:

  • kubectl top to API server: asks
  • HPA and VPA to API server: asks
  • API server to metrics-server: forwards
  • metrics-server to kubelet: scrapes every 15s
  • kubelet to cAdvisor: asks
  • cAdvisor to Containers: reads

Follow one number from a container to your terminal:

  1. Every container runs in a Linux cgroup. The kernel counts the CPU time and the memory of each cgroup, whether anyone is looking or not.
  2. The kubelet reads those counters. For this it has a collector compiled into it, cAdvisor (container advisor); with some runtimes it asks the container runtime over the CRI instead. Either way, the kubelet offers the result on its own HTTPS API (port 10250) at /metrics/resource.
  3. Metrics Server runs as a Deployment in kube-system. It lists the nodes, then scrapes each kubelet's /metrics/resource endpoint on a fixed interval (15 seconds in the standard manifest).
  4. Metrics Server registers itself with the API server as an extension API, metrics.k8s.io/v1beta1. The API server does not know anything about metrics; it simply forwards requests for that API group to the metrics-server Service. This forwarding is called the aggregation layer.
  5. kubectl top, the Horizontal Pod Autoscaler and the Vertical Pod Autoscaler ask the API server for metrics.k8s.io objects, with your normal credentials and normal RBAC.

This design is why nothing in the cluster has to reach into a node to learn its load: components only ever talk to the API server, and one add-on does the collecting.

What exactly is measured

MetricUnit you seeWhat it means
CPUCores, usually millicores: 250m is a quarter of one coreThe average rate of CPU use over the last scrape window, computed from two readings of a counter
MemoryBytes, usually MiThe working set at the moment of the scrape: memory in use that the kernel cannot easily take back. It includes some file cache

Two consequences are worth remembering:

  • CPU needs two readings. A Pod that started a few seconds ago has only one, so kubectl top answers metrics not available yet for it. Wait for the next scrape.
  • The numbers are up to one scrape interval old. kubectl top is a recent snapshot, not a live view like top on Linux.

Metrics Server is not a monitoring system

Metrics Server is not a monitoring systemscrapedlatestscrapedquerieskubeletsCPU and memorymetrics-serverno historykubectl top, HPAwhat is used now?Components/metrics endpointsPrometheusstores historyDashboards, alertswhat happened when?
Metrics Server is not a monitoring system. Metrics Server answers one question: how much is in use right now? History, dashboards and alerts need a monitoring system such as Prometheus, which scrapes the same kubelets itself.

Parts:

  • kubelets (CPU and memory)
  • metrics-server (no history)
  • kubectl top, HPA (what is used now?)
  • Components (/metrics endpoints)
  • Prometheus (stores history)
  • Dashboards, alerts (what happened when?)

Connections:

  • kubelets to metrics-server: scraped
  • metrics-server to kubectl top, HPA: latest
  • Components to Prometheus: scraped
  • kubelets to Prometheus
  • Prometheus to Dashboards, alerts: queries

Metrics Server was built for autoscaling, and kubectl top is a convenient extra. It keeps the latest values in memory and nothing else:

Metrics ServerA monitoring system (Prometheus and others)
AnswersHow much is in use now?What happened, when, and is it getting worse?
StoresLatest values, in memory. A restart loses themEvery sample, on disk, for days or months
MetricsCPU and memory of nodes, Pods and containersThousands: requests, errors, latencies, queue lengths, disk, network
Used bykubectl top, HPA, VPADashboards (Grafana), alerts (Alertmanager), people
In the CKA examYesNo, but know that it exists and why

A monitoring system does not read from Metrics Server. It scrapes the kubelets itself (/metrics/resource and /metrics/cadvisor) and the /metrics endpoint that every cluster component offers. The Metrics Server project says so directly: do not use it as a source for monitoring.

Under the hood · The /metrics endpoints of the cluster components

Every Kubernetes component publishes its own internal numbers in the Prometheus text format: request counts and latencies of the API server, queue depths of the controllers, scheduling attempts, etcd disk sync times.

ComponentEndpoint (kubeadm defaults)
kube-apiserverhttps://<node>:6443/metrics
kube-schedulerhttps://127.0.0.1:10259/metrics
kube-controller-managerhttps://127.0.0.1:10257/metrics
etcdhttp://127.0.0.1:2381/metrics
kubelethttps://<node>:10250/metrics, /metrics/cadvisor, /metrics/resource
kube-proxyhttp://127.0.0.1:10249/metrics

You can read the API server's own metrics, and any kubelet's through the API server's node proxy, without leaving your terminal:

kubectl get --raw /metrics | grep ^apiserver_request_total | head -n 3
kubectl get --raw /api/v1/nodes/node-1/proxy/metrics/resource | grep ^node_

The second command returns exactly what Metrics Server scrapes. It is a quick way to prove that a kubelet is producing numbers when kubectl top shows none.

Installing Metrics Server

kubeadm does not install Metrics Server. Many managed clusters and local tools do (in minikube it is minikube addons enable metrics-server). Without it:

$ kubectl top nodes
error: Metrics API not available

One manifest from the project's releases installs everything:

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
Object it createsWhy it is needed
Deployment metrics-server in kube-system (label k8s-app=metrics-server)The collector itself
Service metrics-server (port 443)The address the API server forwards to
APIService v1beta1.metrics.k8s.ioTells the API server that this API group lives behind that Service
ServiceAccount, ClusterRoles and bindingsLets Metrics Server list nodes and Pods and read nodes/metrics from the kubelets

Check the three things that have to be true before kubectl top works:

kubectl -n kube-system get deployment metrics-server        # READY 1/1
kubectl get apiservice v1beta1.metrics.k8s.io               # AVAILABLE True
kubectl top nodes                                           # numbers, after about 30 seconds

The flags you may have to touch, all in the Deployment's args:

FlagWhat it does
--kubelet-insecure-tlsDo not verify the kubelets' serving certificates. For test clusters only
--kubelet-preferred-address-types=InternalIP,ExternalIP,HostnameWhich node address to scrape. Put InternalIP first when node names do not resolve in DNS
--metric-resolution=15sHow often to scrape. Values below 15s are pointless, because the kubelet does not refresh faster
--secure-port=10250The port Metrics Server itself listens on, which the API server must be able to reach

Using kubectl top

kubectl top nodes                         # every node
kubectl top node node-1                   # one node
kubectl top pods                          # Pods in the current namespace
kubectl top pods -A                       # all namespaces
kubectl top pod web-5d8b6f7c9-4tzjw --containers   # split a Pod into its containers
NAME           CPU(cores)   CPU(%)   MEMORY(bytes)   MEMORY(%)
controlplane   212m         10%      1480Mi          39%
node-1         1630m        81%      2210Mi          58%

For nodes, the percentages are relative to the node's allocatable resources, the part of the machine that Pods may use. Add --show-capacity to compare with the full capacity of the machine instead. Pods have no percentage columns, because a Pod has no size of its own; compare its usage with its requests and limits yourself.

FlagWorks onEffect
--sort-by=cpu or --sort-by=memorynodes, podsHighest first
-l app=webnodes, podsOnly objects with that label
-A, -n <namespace>podsAll namespaces, or one
--containerspodsOne line per container
--sumpodsAdds a total line
--no-headersnodes, podsDrops the header, for scripts
--show-capacitynodesPercentages of capacity, not allocatable

Example · Find the Pod that uses the most CPU

A classic exam task: among the Pods with the label tier=backend, find the one that uses the most CPU and write its name to /opt/answers/top-cpu.txt.

kubectl top pods -A -l tier=backend --sort-by=cpu
NAMESPACE   NAME                      CPU(cores)   MEMORY(bytes)
shop        cart-6c9f7d5b8-x2kqp      1480m        310Mi
billing     invoice-7f6d9c4b5-m8rvw   220m         512Mi
shop        web-5d8b6f7c9-4tzjw       12m          48Mi

The first line is the answer. Write it by hand, or let the shell do it:

kubectl top pods -A -l tier=backend --sort-by=cpu --no-headers | head -n 1 | awk '{print $2}' > /opt/answers/top-cpu.txt
cat /opt/answers/top-cpu.txt

Note the $2: with -A the first column is the namespace. Without -A the name is $1. Read the task twice to see whether it wants CPU or memory, and one namespace or all of them.

Example · Find out why a node is running hot

node-1 is slow. First the node, then the Pods on it, then the containers in the worst Pod:

kubectl top node node-1
kubectl get pods -A --field-selector spec.nodeName=node-1 -o wide      # who lives there
kubectl top pods -A --sort-by=memory | head -n 10                      # the biggest consumers overall
kubectl top pod cart-6c9f7d5b8-x2kqp -n shop --containers

Then compare usage with what the container is allowed:

kubectl get pod cart-6c9f7d5b8-x2kqp -n shop \
  -o jsonpath='{range .spec.containers[*]}{.name}{"\t"}{.resources}{"\n"}{end}'
kubectl describe node node-1 | grep -A 8 "Allocated resources"
kubectl describe node node-1 | grep -A 7 "Conditions"                  # MemoryPressure, DiskPressure, PIDPressure

Memory that climbs steadily towards the limit ends in OOMKilled. CPU that sits exactly at the limit means the container is being throttled. A Pod with no limits at all can starve its neighbours.

When kubectl top does not work

The chain behind one kubectl topaskslooks uppoints toready?scrapeskubectl toperrorAPI serveraggregation layerAPIServicev1beta1.metricsServicemetrics-server:443Podmetrics-server, 1/1?kubeletsport 10250, TLS
The chain behind one kubectl top. When kubectl top fails, walk this chain link by link, starting at kubectl top. Each link has one command that tells you whether it works.

Parts:

  • kubectl top (error)
  • API server (aggregation layer)
  • APIService (v1beta1.metrics)
  • Service (metrics-server:443)
  • Pod (metrics-server, 1/1?)
  • kubelets (port 10250, TLS)

Connections:

  • kubectl top to API server: asks
  • API server to APIService: looks up
  • APIService to Service: points to
  • Service to Pod: ready?
  • Pod to kubelets: scrapes

Walk the chain from left to right. Each error message already tells you which link to look at:

What you seeWhat it meansCheck
error: Metrics API not availableNo APIService for metrics.k8s.io: Metrics Server is not installedkubectl get apiservice | grep metrics
the server is currently unable to handle the request (get nodes.metrics.k8s.io)The APIService exists, but nothing healthy answers behind itkubectl get apiservice v1beta1.metrics.k8s.io shows False (MissingEndpoints) or False (FailedDiscoveryCheck)
Pod metrics-server-... is 0/1 RunningIt cannot scrape the kubelets, so its readiness probe failskubectl -n kube-system logs deploy/metrics-server
error: metrics not available yetMetrics Server is fine, but has fewer than two readings for this Pod or nodeWait 15 to 30 seconds
ForbiddenYour user may not read metrics.k8s.iokubectl auth can-i get pods.metrics.k8s.io

Example · Repair Metrics Server on a kubeadm cluster

kubectl top nodes answers the server is currently unable to handle the request. Follow the chain:

kubectl get apiservice v1beta1.metrics.k8s.io
kubectl -n kube-system get pods -l k8s-app=metrics-server
kubectl -n kube-system logs deploy/metrics-server | tail -n 5
NAME                     SERVICE                      AVAILABLE                  AGE
v1beta1.metrics.k8s.io   kube-system/metrics-server   False (MissingEndpoints)   3m

NAME                              READY   STATUS    RESTARTS   AGE
metrics-server-6f7dd4c4c4-9xw2l   0/1     Running   0          3m

"Failed to scrape node" err="Get \"https://192.168.56.11:10250/metrics/resource\": tls: failed to verify
certificate: x509: cannot validate certificate for 192.168.56.11 because it doesn't contain any IP SANs" node="node-1"

The kubelet certificates cannot be verified. In a lab cluster, add the flag:

kubectl -n kube-system edit deployment metrics-server
    spec:
      containers:
        - name: metrics-server
          args:
            - --cert-dir=/tmp
            - --secure-port=10250
            - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
            - --kubelet-use-node-status-port
            - --metric-resolution=15s
            - --kubelet-insecure-tls          # added

Or without an editor:

kubectl -n kube-system patch deployment metrics-server --type=json \
  -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--kubelet-insecure-tls"}]'
kubectl -n kube-system rollout status deployment metrics-server
kubectl top nodes

If the log instead says no such host or dial tcp ... i/o timeout, the problem is the address or the network: put InternalIP first in --kubelet-preferred-address-types, or look for a firewall or NetworkPolicy that blocks port 10250 between Metrics Server and the nodes.

Checking the components themselves

Resource usage is half of monitoring. The other half is knowing whether the parts that run the cluster are alive. Everything you need is built in:

kubectl get --raw='/readyz?verbose'        # the API server's own checks, one line each
kubectl get --raw='/livez?verbose'
kubectl -n kube-system get pods -o wide    # control plane, CoreDNS, kube-proxy, CNI, metrics-server
kubectl get nodes                          # is every kubelet reporting in?
kubectl describe node node-1               # Conditions, capacity, events
kubectl -n kube-system get lease           # who is the active scheduler and controller manager
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp
SignalHealthyWhat a bad value tells you
/readyz?verboseEvery line [+] ... ok, last line readyz check passedA line with [-] names the failing check, for example etcd
Pods in kube-systemRunning, READY 1/1, restart count stableA growing RESTARTS number means a component is crash looping, even if it is Running right now
Node statusReadyNotReady: the kubelet stopped sending heartbeats. Go to the node: systemctl status kubelet
Node conditionsMemoryPressure, DiskPressure, PIDPressure all FalseTrue means the kubelet is about to evict Pods, or already is
Leases in kube-systemkube-scheduler and kube-controller-manager have a holder and a fresh renew timeNo holder, or a stale time: that component is not running

When a control plane Pod is unhealthy, the next step is its logs: kubectl -n kube-system logs <pod>, or crictl logs on the node when the API server itself is down. Logs are the subject of the next lesson.

Tricks

Common mistakes

  • Expecting history. Metrics Server knows the present only. "What used the memory last night" needs a monitoring system that was already running last night.
  • Reading kubectl top as requests. It shows real usage. For "Insufficient cpu" scheduling problems, look at Allocated resources in kubectl describe node.
  • Forgetting the namespace column. With -A, the Pod name is the second column. An awk '{print $1}' then writes the namespace into your answer file.
  • Sorting by the wrong resource. Tasks ask for CPU or for memory. --sort-by takes exactly cpu or memory.
  • Leaving --kubelet-insecure-tls on in production. It turns off the check that Metrics Server is really talking to your kubelets. It is acceptable in a lab, not on a real cluster.
  • Restarting things when the answer is "wait". After an install, a rollout or a new Pod, metrics need two scrapes. metrics not available yet usually fixes itself in under a minute.
  • Trusting Running. A control plane Pod can be Running with 40 restarts. Read the RESTARTS column and the node conditions, not only the status.

Recap

  • The kubelet (with cAdvisor inside it) measures CPU and memory of every container on its node.
  • Metrics Server scrapes every kubelet, keeps the latest values in memory and serves them as metrics.k8s.io through the API server's aggregation layer.
  • kubectl top nodes and kubectl top pods read that API; --sort-by, -l, -A, --containers and --no-headers answer most exam tasks in one line.
  • When it fails: APIService, then the metrics-server Pod, then its logs. On kubeadm the usual cause is the kubelet certificate.
  • Component health comes from /readyz?verbose, the Pods in kube-system, node conditions and leases.
  • History, dashboards and alerts are the job of a monitoring system such as Prometheus, not of Metrics Server.

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

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

  • Read live CPU and memory numbers with kubectl top to find the hungriest pod and the busiest container.

    Investigate · Level 1 · warm-up · target 10 min

  • Shape kubectl's output with jsonpath, custom columns, sorting and field selectors to answer four questions about a cluster without scrolling through YAML.

    Investigate · Level 2 · standard · target 20 min

Discussion

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