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
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 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:
| Question | Where 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
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:
- 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.
- 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. - Metrics Server runs as a Deployment in
kube-system. It lists the nodes, then scrapes each kubelet's/metrics/resourceendpoint on a fixed interval (15 seconds in the standard manifest). - 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 themetrics-serverService. This forwarding is called the aggregation layer. kubectl top, the Horizontal Pod Autoscaler and the Vertical Pod Autoscaler ask the API server formetrics.k8s.ioobjects, 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
| Metric | Unit you see | What it means |
|---|---|---|
| CPU | Cores, usually millicores: 250m is a quarter of one core | The average rate of CPU use over the last scrape window, computed from two readings of a counter |
| Memory | Bytes, usually Mi | The 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 topanswersmetrics not available yetfor it. Wait for the next scrape. - The numbers are up to one scrape interval old.
kubectl topis a recent snapshot, not a live view liketopon Linux.
Metrics Server is not a monitoring system
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 Server | A monitoring system (Prometheus and others) | |
|---|---|---|
| Answers | How much is in use now? | What happened, when, and is it getting worse? |
| Stores | Latest values, in memory. A restart loses them | Every sample, on disk, for days or months |
| Metrics | CPU and memory of nodes, Pods and containers | Thousands: requests, errors, latencies, queue lengths, disk, network |
| Used by | kubectl top, HPA, VPA | Dashboards (Grafana), alerts (Alertmanager), people |
| In the CKA exam | Yes | No, 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.
| Component | Endpoint (kubeadm defaults) |
|---|---|
| kube-apiserver | https://<node>:6443/metrics |
| kube-scheduler | https://127.0.0.1:10259/metrics |
| kube-controller-manager | https://127.0.0.1:10257/metrics |
| etcd | http://127.0.0.1:2381/metrics |
| kubelet | https://<node>:10250/metrics, /metrics/cadvisor, /metrics/resource |
| kube-proxy | http://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 creates | Why 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.io | Tells the API server that this API group lives behind that Service |
| ServiceAccount, ClusterRoles and bindings | Lets 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:
| Flag | What it does |
|---|---|
--kubelet-insecure-tls | Do not verify the kubelets' serving certificates. For test clusters only |
--kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname | Which node address to scrape. Put InternalIP first when node names do not resolve in DNS |
--metric-resolution=15s | How often to scrape. Values below 15s are pointless, because the kubelet does not refresh faster |
--secure-port=10250 | The 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.
| Flag | Works on | Effect |
|---|---|---|
--sort-by=cpu or --sort-by=memory | nodes, pods | Highest first |
-l app=web | nodes, pods | Only objects with that label |
-A, -n <namespace> | pods | All namespaces, or one |
--containers | pods | One line per container |
--sum | pods | Adds a total line |
--no-headers | nodes, pods | Drops the header, for scripts |
--show-capacity | nodes | Percentages 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
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 see | What it means | Check |
|---|---|---|
error: Metrics API not available | No APIService for metrics.k8s.io: Metrics Server is not installed | kubectl 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 it | kubectl get apiservice v1beta1.metrics.k8s.io shows False (MissingEndpoints) or False (FailedDiscoveryCheck) |
Pod metrics-server-... is 0/1 Running | It cannot scrape the kubelets, so its readiness probe fails | kubectl -n kube-system logs deploy/metrics-server |
error: metrics not available yet | Metrics Server is fine, but has fewer than two readings for this Pod or node | Wait 15 to 30 seconds |
Forbidden | Your user may not read metrics.k8s.io | kubectl 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
| Signal | Healthy | What a bad value tells you |
|---|---|---|
/readyz?verbose | Every line [+] ... ok, last line readyz check passed | A line with [-] names the failing check, for example etcd |
Pods in kube-system | Running, READY 1/1, restart count stable | A growing RESTARTS number means a component is crash looping, even if it is Running right now |
| Node status | Ready | NotReady: the kubelet stopped sending heartbeats. Go to the node: systemctl status kubelet |
| Node conditions | MemoryPressure, DiskPressure, PIDPressure all False | True means the kubelet is about to evict Pods, or already is |
Leases in kube-system | kube-scheduler and kube-controller-manager have a holder and a fresh renew time | No 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 topas requests. It shows real usage. For "Insufficient cpu" scheduling problems, look atAllocated resourcesinkubectl describe node. - Forgetting the namespace column. With
-A, the Pod name is the second column. Anawk '{print $1}'then writes the namespace into your answer file. - Sorting by the wrong resource. Tasks ask for CPU or for memory.
--sort-bytakes exactlycpuormemory. - Leaving
--kubelet-insecure-tlson 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 yetusually fixes itself in under a minute. - Trusting
Running. A control plane Pod can beRunningwith 40 restarts. Read theRESTARTScolumn 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.iothrough the API server's aggregation layer. kubectl top nodesandkubectl top podsread that API;--sort-by,-l,-A,--containersand--no-headersanswer most exam tasks in one line.- When it fails: APIService, then the
metrics-serverPod, then its logs. On kubeadm the usual cause is the kubelet certificate. - Component health comes from
/readyz?verbose, the Pods inkube-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.