How to allocate 50% CPU resource to docker container via `docker run`?

cpu-shares is a 'relative weight', relative to the default setting of 1024, so if you had two containers running on the same core, you could give them the CPU 50-50 or 80-20 or whatever you wanted by adjusting the numbers. It is an integer.

You cannot give an overall limit, as you want to, using this flag, but you can restrict the set of CPUs that the container runs on using --cpuset mentioned here.

The number 1024 is in the Cgroups docs.

This blog post from Marek Goldmann explains resource management in Docker.

See also Setting absolute limits on CPU for Docker containers, which says it can be done with lxc (older Docker implementation) but not libcontainer (current Docker implementation).


It depends on the environment, so there is no straight answer but keep reading.

From the docker run --help command:

-c, --cpu-shares=0         CPU shares (relative weight)

Since Docker is based on cgroups. The CPU will be distributed among the running containers. By default the value is 1024.

cat /sys/fs/cgroup/cpu/docker/cpu.shares
1024



So, if we have 2 containers, one for the database and one more for the web server

sudo docker run -c 614 -dit --name db postgres /postgres.sh
sudo docker run -c 410 -dit --name web nginx /nginx.sh

Will give 60% to the db container (614 is 60% of 1024) and 40% to the web container.



For further reading see:

  • cpu shares cgroups documentation.
  • The cpuset option: --cpuset="" CPUs in which to allow execution (0-3, 0,1)
  • Resource management in Docker post.
  • Chapter 3 Configuring Docker Containers of the book Orchestating Docker by Shrikrishna Holla.

Tags:

Docker