Managing Container Resources
CPU Usage Reservations and Limits
Docker provides several options to control how containers use CPU resources. These options map directly to Linux cgroups and allow you to express CPU limits, affinities, and relative priorities. The following examples demonstrate the most commonly used mechanisms.
Limiting the maximum CPU time a container can use
You can limit how much CPU time a container may consume using the --cpus flag. This option sets an upper bound on CPU usage, expressed as a fractional number of CPUs. For example, allowing a container to use up to one and a half CPUs:
docker run -d --cpus="1.5" nginx
This doesn't reserve CPUs exclusively. Instead, it caps the container's total CPU time using the Linux CFS quota and period mechanism. The container may use up to 150% of a single CPU's time, distributed across any CPUs it's allowed to run on. For example, it may fully utilize one CPU and partially utilize another, as long as the total CPU time doesn't exceed the configured limit.
By default, Docker uses a CFS scheduling period of 100 ms. When a container is limited to 1.5 CPUs, it's allowed to consume up to 150 ms of total CPU time during each 100 ms period. This CPU time can be distributed across multiple cores, and once the quota is exhausted, the container is throttled until the next scheduling period.
Docker also offers --cpu-quota and --cpu-period for more granular control, but --cpus is simpler for most use cases.
--cpu-quota: Sets the total CPU time (in microseconds) that a container can use during each scheduling period.--cpu-period: Sets the length of the scheduling period (in microseconds). The default is 100,000 microseconds (100 ms).
Restricting which CPUs a container can run on
You can restrict a container to specific CPU cores using the --cpuset-cpus flag. For example, to allow a container to run only on CPU cores 1 and 3:
docker run -d --cpuset-cpus="1,3"Painless Docker - 2nd Edition
A Comprehensive Guide to Mastering Docker and its EcosystemEnroll now to unlock all content and receive all future updates for free.
Hurry! This limited time offer ends in:
To redeem this offer, copy the coupon code below and apply it at checkout:
