Docker Community Forums

Share and learn in the Docker community.

Set hard CPU limits in a Docker Swarm

I am trying to set hard CPU and memory limits in a Docker Swarm consisting of three VMs. I am using the cpu and memory limit configurations suggested by docker documentation in my docker-compose.yml file. My docker-compose.yml file looks like

version: "3"
    # replace username/repo:tag with your name and image details
    image: hifzak/testing:part2
      replicas: 10
          cpus: "0.5"
          memory: 4M	
        condition: on-failure

The CPU and memory resources of my host machine and the VMs are shown in the figure below. My host machine has 4 CPUs and all the VMs have 1 CPU each.

enter image description here

To figure out if Docker containers can limit their resources, I am running a test program with an infinite loop in my swarm. One of the snapshots from my experiments is shown below. It shows docker stats results on the three VMs (VM1: bottom left, VM2: top right, VM3: bottom right).

enter image description here

Looking at the results, I have a few questions.

  1. How is the CPU limited to 50% for each container?
  2. Each VM has 1 CPU then how come on one VM, docker containers CPU% sum exceeds 100%?
  3. In the image above, I have 7 docker containers running and sum of CPU% for all of them is 22+21+88+52+66+78+76 = 403 approx. which
    means that the swarm is using 4 cores instead of 3. Is it
    possible that docker allows the swarm to use CPU resources of the
    host machine as well if needed?

Can anybody please guide me with these questions? Thank you.

I think you are looking at it incorrectly, the cpu percentage is reading from the .5 cpu.
think of it this way;
container #1 cpu limit 1.0 30% load
container #2 cpu limit .5 60% load

the load is based on the amount of cpu it can consume. so container #2 thinks it is at 100% when it can consume all of the .5 cpu cycles