How can I set docker affinity in docker correctly?

597 Views Asked by At

I want to limit the number of cores that a docker container uses.

I have found the documentation and I can see that I can use --cpus as in

docker run -it --cpus=".5" ubuntu /bin/bash

but I don't understand what this setting actually represents. In the documentation example it uses 0.5 which indicates 50% of the CPU (so a percentage)

however in this other example it uses the command

--cpus=2

to set "the maximum number of CPUs that a container can use. For example, to limit a container to using two CPUs"

so which is which? a percentage or not

In my case for example I have a workstation of X cores and I want to limit it to Y cores. What should I put?

1

There are 1 best solutions below

2
KamilCuk On

From https://docs.docker.com/config/containers/resource_constraints/ :

--cpus=
Specify how much of the available CPU resources a container can use. For instance, if the host machine has two CPUs and you set --cpus="1.5", the container is guaranteed at most one and a half of the CPUs. This is the equivalent of setting --cpu-period="100000" and --cpu-quota="150000". --cpu-period=
Specify the CPU CFS scheduler period, which is used alongside --cpu-quota. Defaults to 100000 microseconds (100 milliseconds). Most users do not change this from the default. For most use-cases, --cpus is a more convenient alternative. --cpu-quota=
Impose a CPU CFS quota on the container. The number of microseconds per --cpu-period that the container is limited to before throttled. As such acting as the effective ceiling. For most use-cases, --cpus is a more convenient alternative.

--cpus specifies --cpu-quota which specifies the maximum cpu time the container will get per some period.

Also https://kernel.googlesource.com/pub/scm/linux/kernel/git/glommer/memcg/+/cpu_stat/Documentation/cgroups/cpu.txt .

cpu.cfs_quota_us [..] One should note that this represents aggregate time over all CPUs in the system. Therefore, in order to allow full usage of two CPUs, for instance, one should set this value to twice the value of cfs_period_us.

Effectively, setting --cpus=2 will set --cpu-quote = 2 * --cpu-period which means that each 100 milliseconds the process will be maximally able to use 200 milliseconds on all cores, which effectively limits it to 2 cores.

so which is which?

Both. A "core" is a virtual CPU. CPU here represents a core if your computer has like one cpu with many cores.

What should I put?

--cpus=Y or --cpuset-cpus=0-Y.