Sobes.tech
Junior — Middle

How does Docker manage and limit the use of resources such as CPU and memory for containers?

sobes.tech AI

Answer from AI

To manage and limit Docker container system resources, the following methods can be used:

  • CPU Limitation:

    • --cpus — limits the number of CPUs available to the container.
    • --cpu-shares — relative priority of CPU usage.
    • --cpu-quota and --cpu-period — finer control over CPU time.
  • Memory Limitation:

    • --memory — maximum amount of memory available to the container.
    • --memory-swap — swap memory limit.
  • Input/Output Limitation:

    • --blkio-weight — I/O block weight priority.
  • Network Limitation:

    • Using network policies and restrictions via Docker network or external tools.

Example of running a container with resource limits:

docker run --cpus="1.5" --memory="512m" nginx

sobes.tech AI

Answer from AI

Docker manages and limits container resources using Linux kernel features such as cgroups and namespaces.

  • CPU: you can limit the number of available processor cores or the CPU share that a container can use using flags like --cpus, --cpu-shares, --cpu-quota, and --cpu-period when starting a container.

  • Memory: memory limits are set with --memory (maximum memory size) and --memory-swap (swap memory size).

Example of running a container with resource limits:

docker run --cpus="1.5" --memory="512m" nginx

In this example, the container can use up to 1.5 CPUs and 512 MB of RAM.

Thus, Docker uses cgroups to control and isolate resources so that containers do not exceed their set limits and do not interfere with other services.