How to Limit CPU and Memory Usage in Docker Containers

How to Limit CPU and Memory Usage in Docker Containers
Freepik
Isolate processes and guarantee resources with Docker containers

Introduction

Docker containers are a great way to isolate processes from each other on a single host. This can be especially useful when running multiple processes that are CPU or memory intensive, as it ensures that one process cannot starve the others of resources.

It is also possible to limit the amount of CPU or memory that a Docker container can use. This can be useful to prevent a single process from using too much of the host's resources or to guarantee that a container always has a minimum amount of resources available to it.

CPU Limits

CPU limits can be set using the --cpu-period and --cpu-quota parameters. The --cpu-period parameter sets the length of a CPU cycle in microseconds. The --cpu-quota parameter sets the number of cycles that a container is allowed to use in that period.

For example, to limit a container to using no more than 50% of a single CPU core, you would use the following parameters:

--cpu-period=50000
--cpu-quota=25000

You can also use the --cpus parameter to set the maximum number of CPUs that a container can use. For example, to limit a container to using two CPUs, you would use the following parameter:

--cpus=2

Memory Limits

Memory limits can be set using the --memory parameter. This parameter sets the maximum amount of memory that a container can use, in bytes.

For example, to limit a container to using no more than 512 MB of memory, you would use the following parameter:

--memory=512m

You can also use the --memory-swap parameter to set the maximum amount of memory and swap that a container can use. This parameter is set in the same way as the --memory parameter, in bytes.

For example, to limit a container to using no more than 512 MB of memory and swap, you would use the following parameter:

--memory-swap=512m

Example Docker command:

docker run --name my-container --cpu-period=50000 --cpu-quota=25000 --memory=512m my-image

Example docker-compose configuration:

version: '3'

services:
  my-service:
    image: my-image
    cpu_period: 50000
    cpu_quota: 25000
    memory: 512m

Conclusion

Docker containers are a great way to isolate processes from each other on a single host. CPU and memory limits can be set to ensure that one process cannot starve the others of resources or to guarantee that a container always has a minimum amount of resources available to it.


If you want to stay up-to-date with the latest insights in Artificial Intelligence, DevOps, Cloud, Linux, Programming, Blockchain, Productivity, and more, subscribe to my Weekly Newsletter. You’ll also get access to my tutorials, tips, and guides, as well as resources from other experts in these fields.

Follow me on Twitter and GitHub!