I want to limit a service to half the processing power of the machine it is hosted in.
If I have a machine with 8 cores, --cpus
should be set to 4.0
, but if I have only 4, it should be 2.0
.
Is it possible to do this using just a docker-compose.yml
file?
2
Answers
You can use a simple script to get this information and inject it into compose. This will not work for swarm mode:
and then use the variable in compose:
Explanaition of the bash command:
/proc/cpuinfo
contains information about every core in the system. Searching for "processor" yields one match per core.-c
flag returns the number of matches instead of the matched lines.$()
runs the command in a subshell, so$(grep -c "processor" /proc/cpuinfo)
will evaluate to let’s say 4.$(())
can do simple calculation in bash so we divide the found cores by two and get our result. One caveat is that this only works with core counts divisible by 2, because it only does integer arithmetic.Actually I was mistaken. There is a way to set half of the CPU. It is just not in the usual place, so I missed it. Looking again at the compose file specification there is an attribute making this possible. I haven’t used this myself so I am not sure if this works with swarm mode, but according to the documentation it should work like this:
You can also find that there is a
cpu_shares
attribute that could be useful.