skip to Main Content

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


  1. You can use a simple script to get this information and inject it into compose. This will not work for swarm mode:

    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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search