In this short tutorial, we'll learn how to limit Docker container memory and CPU usage. In some cases, this can be very useful, for example when we have limited resources and microservice architecture with one of the services with a tendency to expand its resource consumption. This would potentially block or slow down other services, so we'll show here how to prevent this.
2. Limit Memory Usage
For the purpose of the example, let's limit the memory that the container can use to 1024 megabytes. To achieve this, there's an option -m that is used with the docker run command:
$ docker run -m 1024m nginx
We can also set a memory reservation that is sometimes called soft limit. It becomes active when the Docker detects low memory on the host machine:
$ docker run -m 1024m --memory-reservation=256m nginx
3. Limit CPU Usage
Docker by default has unlimited access to the computing power of the host machine. We can set the CPUs limit using the --cpus parameter with the docker run command. For example, let's constrain our container to use at most four CPUs:
$ docker run --cpus=4 nginx
There's also a flag that is used to increase or reduce the container’s weight, and give it access to a greater or lesser proportion of the host machine’s CPU cycles. This means that we can specify the priority of CPU allocation, but it does not guarantee or reserve any specific CPU access. The default is 1024, higher numbers mean higher priority.
$ docker run --cpus=4 --cpu-shares=1050 nginx
CPU shares are only enforced when CPU cycles are constrained. When plenty of CPU cycles are available, all containers use as much CPU as they need. In that way, this is a soft limit. --cpu-shares does not prevent containers from being scheduled in swarm mode.
We can also set the memory and CPU limits in docker-compose file. You can learn here how to do that.
4. Check and Verify Docker Container Memory and CPU Usage
Since we set the memory and CPU limits, we can verify them using the docker stats command:
$ docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 17071c2f2dc8 goos_stack_service.1.p37ad21r1qih16ynif94sk2zj 0.00% 2.578MiB / 1024MiB 0.50% 936B / 0B 0B / 0B 2
In this tutorial, we learned how to set memory and CPU limits for Docker containers using docker run command. We also mentioned how do we set soft limits for both memory and CPU shares.