Use context: kubectl config use-context k8s-c1-H
The metrics-server has been installed in the cluster. Your college would like to know the kubectl commands to:
- show Nodes resource usage
- show Pods and their containers resource usage
Please write the commands into /opt/course/7/node.sh
and /opt/course/7/pod.sh
.
Monitoring Resource Usage in Kubernetes with kubectl top
Monitoring resource usage is crucial for maintaining a healthy and efficient Kubernetes cluster. In this guide, we’ll explore how to use the kubectl top
command to view resource consumption, such as CPU and memory usage, for both nodes and pods.
Step 1: Understanding the kubectl top Command
The kubectl top
command is used to display resource usage in a Kubernetes cluster. This command relies on the Metrics Server, which must be correctly configured and running in your cluster. You can see the available options by running:
1 2 3 4 5 |
➜ kubectl top -h |
This displays help information about the kubectl top
command, showing the available options and usage examples. The two main subcommands are:
node
: Display resource usage of nodes.pod
: Display resource usage of pods.
Step 2: Checking Node Resource Usage
To monitor the resource usage across all nodes in your cluster, use the following command:
1 2 3 4 5 |
➜ kubectl top node |
This command provides an overview of CPU and memory usage for each node. For example:
1 2 3 4 5 6 7 8 |
NAME CPU(cores) CPU% MEMORY(bytes) MEMORY% cluster1-controlplane1 178m 8% 1091Mi 57% cluster1-node1 66m 6% 834Mi 44% cluster1-node2 91m 9% 791Mi 41% |
This output shows the resource usage for each node, including the CPU and memory consumption as both absolute values and percentages.
To automate this monitoring, you can create a shell script:
1 2 3 4 5 6 |
# /opt/course/7/node.sh kubectl top node |
Step 3: Checking Pod Resource Usage
Similarly, you can monitor the resource usage of individual pods using the following command:
1 2 3 4 5 |
➜ kubectl top pod --containers=true |
The --containers=true
flag includes container-level metrics within each pod. This is useful for detailed monitoring, especially in multi-container pods. The help command provides more details:
1 2 3 4 5 |
➜ kubectl top pod -h |
This output includes options for customizing the output, such as removing headers or specifying particular containers within a pod. To automate pod resource monitoring, create another script:
1 2 3 4 5 6 |
# /opt/course/7/pod.sh kubectl top pod --containers=true |
By using the kubectl top
command, you can easily monitor the resource usage of nodes and pods in your Kubernetes cluster. This is vital for identifying resource bottlenecks and ensuring that your applications run smoothly.