Limit the CPU a Docker Container Can Use with --cpus
Cap a container's CPU time with docker run --cpus 0.5, which sets a quota in cgroup v2. nproc still reports every CPU; --cpuset-cpus changes what is visible.
A container should not use more than half a core, or more than one core, however busy the host is.
docker run --rm --cpus 0.5 alpine:3.20 cat /sys/fs/cgroup/cpu.max
docker run --rm --cpus 2 alpine:3.20 cat /sys/fs/cgroup/cpu.max
docker run --rm --cpus 0.5 alpine:3.20 nproc
docker run --rm --cpuset-cpus 0 alpine:3.20 nproc50000 100000
200000 100000
10
1--cpus 0.5 becomes a quota in the container's cgroup: cpu.max reads 50000 100000, which is 50000 microseconds of CPU time per 100000 microsecond period, and --cpus 2 gives 200000 100000. The quota throttles the process and hides nothing, so nproc still printed 10 in the run. --cpuset-cpus 0 is the option that restricts which CPUs are used, and nproc then printed 1. See Resource constraints in the Docker documentation.
A program that sizes its thread pool from the CPU count sees the host's count under --cpus and can start too many workers; set the pool size explicitly. The file path cpu.max is for cgroup v2, and cgroup v1 hosts use cpu.cfs_quota_us. Docker Desktop applies the limit inside its virtual machine.