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?
No this is not possible only using docker-compose.yml
. You can however use a simple script to get this information and inject it into compose:
CPUS="$(($(grep -c "processor" /proc/cpuinfo)/2))" docker-compose up -d
and then use the variable in compose:
services:
frontend:
image: awesome/webapp
deploy:
resources:
limits:
cpus: ${CPUS}
memory: 50M
pids: 1
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:
services:
frontend:
image: awesome/webapp
cpu_percent: 50
You can also find that there is a cpu_shares
attribute that could be useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.