Installing sysstat Package
To use cpustat in a Debian-based container environment, the sysstat package (which includes cpustat) must be installed. For Debian/Ubuntu systems, run:
sudo apt-get update && sudo apt-get install -y sysstat
This installs the necessary tools to monitor CPU usage.
Running cpustat in Docker Containers
There are two common approaches to execute cpustat within a Docker container:
cpustat directly. First, get the container ID/name using docker ps, then execute:docker exec -it <container_id_or_name> /bin/bash
cpustat -c 1 5 # Displays CPU stats every second for 5 iterations
docker-compose.yml to run cpustat continuously alongside your application. For example:version: '3'
services:
myservice:
image: myimage
command: /bin/bash -c "while true; do cpustat -c 1 5; sleep 1; done"
Run with docker-compose up to start the service.Running cpustat in Kubernetes Pods
In Kubernetes, you can monitor container CPU usage by deploying cpustat as an Init Container (runs before the main container) or a Sidecar Container (runs alongside the main container):
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
initContainers:
- name: cpustat-init
image: sysstat
command: ["sh", "-c", "while true; do cpustat -c 1 5; sleep 1; done"]
containers:
- name: mycontainer
image: myimage
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myimage
- name: cpustat-sidecar
image: sysstat
command: ["sh", "-c", "while true; do cpustat -c 1 5; sleep 1; done"]
Apply the configuration with kubectl apply -f mypod.yaml.Permission Considerations
cpustat requires elevated privileges to access CPU statistics. When running in a container:
--privileged=true for Docker to grant full access to host resources (not recommended for production due to security risks).--cap-add=SYS_ADMIN to add specific capabilities required for monitoring.securityContext to include privileged: true or appropriate capabilities.Practical Use Cases
cpustat -c 1 to view real-time CPU utilization (user/system/idle time) for containers. This helps identify processes consuming excessive CPU.cron to log data hourly) to adjust container resource limits (e.g., --cpus in Docker, resources.limits.cpu in Kubernetes).cpustat to detect sudden CPU spikes caused by misbehaving applications or processes.