Introduction
In this lab, you’ll limit the CPU usage of a Docker container that consumes excessive CPU resources.
Scenario
A container named cpu_test is running from the myapp:cpu image and performs CPU-intensive computations. When monitored with docker stats, the container regularly consumes 150–200% CPU, utilizing multiple CPU cores and impacting other services on the host.
Task
Recreate the container with a CPU limit of 500m CPU so that docker stats reports CPU usage consistently below 60% during validation.
Solution
Let’s check the container’s current CPU usage.
$ docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
dec7403ffc96 cpu_test 199.78% 6.453MiB / 1.042GiB 0.60% 946B / 126B 0B / 0B 4Stop and remove the existing container.
docker stop dec
docker rm decCheck current CPU limits:
docker inspect cpu_test | grep -i cpu"Path": "/app/cpu_workload",
"Name": "/cpu_test",
"CpuShares": 0,
"NanoCpus": 0,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"CpuCount": 0,
"CpuPercent": 0,
"/app/cpu_workload"
"Image": "myapp:cpu",Since all CPU-related settings are 0, no CPU limits are applied.
Recreate the container with a limit of 0.5 CPU (500m).
docker run -d \
--name cpu_test \
--cpus 0.5 \
myapp:cpuVerify the new CPU limit.
$ docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
8640f9d896f7 cpu_test 50.06% 6.473MiB / 1.041GiB 0.61% 876B / 126B 0B / 0B 4The container now uses approximately 50% CPU, confirming that the --cpus 0.5 limit has been applied successfully.