Monitoring memory or CPU usage in a Pod is crucial to do any Kind of work in Kubernetes and make our application are reliables.
The most basic command that we can use to do some monitoring is kubectl top But before, you need to check ...
Metrics Server
Before you can fetch memory metrics, ensure that the Metrics Server is installed and running in your cluster. The kubectl top command depends on it to retrieve live CPU and memory statistics.
kubectl get deployment metrics-server -n kube-system
If it’s not installed, you can add it using:
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
Note: The Metrics Server can take a couple of minutes to install, be patient.
How to use Kubectl top
To check the memory (and CPU) usage of a specific pod, use the following command:
kubectl top pod <pod-name> --namespace=<namespace>
Replace:
<pod-name> with the name of your pod
<namespace> with the namespace the pod is running in
Example:
kubectl top pod nginx-deployment-5c689d4b4b-lv9xl --namespace=default
Output:
NAME CPU(cores) MEMORY(bytes)
nginx-deployment-5c689d4b4b-lv9xl 5m 22Mi
This output shows the live memory usage in MiB and CPU usage in millicores.
To List memory usage for all pods in a namespace:
kubectl top pod --namespace=<namespace>
To List all pod metrics across all namespaces:
kubectl top pod --all-namespaces
To Sort by memory usage (Linux only):
kubectl top pod --all-namespaces | sort -k4 -h
Get node-level memory metrics:
kubectl top node
Troubleshooting
If kubectl top returns an error like:
Error from server (NotFound): the server could not find the requested resource (get services http:heapster:)
It typically means:
That rhe Metrics Server isn’t installed or isn’t working correctly.
The cluster version is incompatible with your Metrics Server version.
Check the logs of the Metrics Server:
kubectl logs -n kube-system deploy/metrics-server