Limit docker container CPU usage
Providing unlimited host CPU usage to the docker containers may lead to performance issues. By default, each container’s access to the host’s CPU cycles is unlimited. To avoid this we can set define how much CPU the docker container can utilize. When you run a docker container, we can use various CPU related options to achieve this.
Allocating CPU resources
To allocation how much CPU a container can use, we can use the option –cpus. For example, let’s the host machine has 1 CPU and if you want your container to utilize 40% of the CPU, the command would be:
docker run -it --cpus=".4" ubuntu
For 1 CPU out of 2 CPUs:
docker run -it --cpus="1" ubuntu
Allocating CPU cycles
To allocate CPU cycles we use –cpu-shares option. By default it’s 1024. To run a container with 900 CPU shares, we can use the following command.
docker run -it --cpus-shares="900" ubuntu
Allocating CPU period
We can specify the CPU usage time using –cpu-period option. Default value is 100 milliseconds.
docker run -it --cpu-period=50000 ubuntu
Here the period is set to 50000 microseconds.
Allocating CPU quota
We can impose a quote on the CPU using –cpu-quota option.
docker run -it --cpu-quota=50000 ubuntu
Here the quota is set to 50000 microseconds.
In most of the cases –cpus is an easy option for restricting CPU usage.