乐闻世界logo
搜索文章和话题

How do you limit the CPU and memory usage of a Docker container?

1个答案

1

When running Docker containers, it is crucial to limit their CPU and memory usage to prevent one container from consuming excessive resources and affecting the operation of other containers. Docker offers various methods to limit container resource usage, such as directly setting parameters with the docker run command.

Limiting CPU Usage:

  1. --cpus Parameter: This parameter allows you to restrict the number of CPU cores a container can utilize. For example, to limit a container to a maximum of 1.5 CPU cores, you can use the following command:
bash
docker run --cpus="1.5" <image>
  1. --cpuset-cpus Parameter: This parameter enables binding a container to specific CPU cores. For instance, to run a container exclusively on CPU 0 and CPU 2, you can use:
bash
docker run --cpuset-cpus="0,2" <image>

Limiting Memory Usage:

  1. -m or --memory Parameter: This parameter restricts the maximum amount of memory a container can consume. For example, to limit a container to a maximum of 500MB of memory, you can use:
bash
docker run -m="500m" <image>
  1. --memory-swap Parameter: This parameter defines the total size of memory plus swap space. For example, you can configure memory to 300MB and swap space to 200MB, totaling 500MB:
bash
docker run -m="300m" --memory-swap="500m" <image>

Example:

Suppose we want to run a web application container using the Python Flask framework, limiting it to a maximum of 50% CPU resources and 250MB of memory. We can start the container with the following command:

bash
docker run --cpus="0.5" -m="250m" my-flask-app

By implementing this approach, we can effectively manage container resource usage, ensuring that other components of the system remain stable and operational.

2024年8月9日 14:07 回复

你的答案