0
0
DockerHow-ToBeginner · 3 min read

How to Limit CPU Usage for Docker Containers

To limit a container's CPU usage in Docker, use the --cpus flag to set the number of CPUs or --cpu-quota and --cpu-period to control CPU time. You can also use --cpuset-cpus to restrict the container to specific CPU cores.
📐

Syntax

Docker provides several flags to limit CPU usage for containers:

  • --cpus=<value>: Limits the number of CPUs. For example, --cpus=1.5 allows 1.5 CPUs.
  • --cpu-quota=<microseconds>: Sets the total available CPU time in microseconds during a period.
  • --cpu-period=<microseconds>: Defines the period for how often the quota is enforced (default 100000).
  • --cpuset-cpus=<cpus>: Restricts the container to specific CPU cores, e.g., 0,1.
bash
docker run --cpus=1.5 myimage

docker run --cpu-quota=150000 --cpu-period=100000 myimage

docker run --cpuset-cpus="0,1" myimage
💻

Example

This example runs an Ubuntu container limited to 0.5 CPU and restricted to CPU core 0. It shows how to apply CPU limits and verify them inside the container.

bash
docker run -it --rm --cpus=0.5 --cpuset-cpus=0 ubuntu bash

# Inside the container, run:
top

# Observe CPU usage limited to half a CPU on core 0
⚠️

Common Pitfalls

Common mistakes when limiting CPU in Docker include:

  • Using --cpu-quota without setting --cpu-period, which defaults to 100000 microseconds but can cause confusion.
  • Setting --cpus to a value higher than available CPUs, which has no effect.
  • Not understanding that --cpuset-cpus restricts cores but does not limit CPU time.
  • Expecting CPU limits to guarantee exact CPU usage; they only set maximum allowed usage.
bash
docker run --cpu-quota=50000 myimage  # Correct: cpu-period defaults to 100000, so quota is 50ms per 100ms (50% CPU)

docker run --cpu-quota=50000 --cpu-period=100000 myimage  # Correct: explicit period and quota
📊

Quick Reference

FlagDescriptionExample
--cpusLimit number of CPUs--cpus=1.5
--cpu-quotaCPU time quota in microseconds--cpu-quota=150000
--cpu-periodCPU quota period in microseconds--cpu-period=100000
--cpuset-cpusSpecify CPU cores--cpuset-cpus="0,1"

Key Takeaways

Use --cpus to easily limit the number of CPUs a container can use.
Combine --cpu-quota and --cpu-period for fine-grained CPU time control.
Use --cpuset-cpus to restrict containers to specific CPU cores.
CPU limits set maximum usage but do not guarantee exact CPU consumption.
Always specify --cpu-period when using --cpu-quota to avoid confusion.