There are many cases in which we need to limit the usage of resources on the docker host machine.
In this tutorial, we’ll learn how to set the memory and CPU limit for docker containers.
We can set the resource limits directly using the docker run command. It’s a simple solution. However, the limit will apply only to one specific execution of the image.
For instance, let’s limit the memory that the container can use to 512 megabytes. To constrain memory, we need to use the m parameter:
$ docker run -m 512m nginx
We can also set a soft limit called a reservation. It’s activated when docker detects low memory on the host machine:
$ docker run -m 512m --memory-reservation=256m nginx
By default, access to the computing power of the host machine is unlimited. **We can set the CPUs limit using the cpus parameter. **For example, let’s constrain our container to use at most two CPUs:
$ docker run --cpus=2 nginx
We can also specify the priority of CPU allocation. The default is 1024, higher numbers are higher priority:
$ docker run --cpus=2 --cpu-shares=2000 nginx
Similarly to the memory reservation, CPU shares play the main role when computing power is scarce and needs to be divided between competing processes.
#docker #devops