Sobes.tech
Middle

How is resource limitation implemented in Docker?

sobes.tech AI

Answer from AI

Docker uses cgroups (control groups) and namespaces to limit and isolate container resources.

  • cgroups allow limiting and accounting for resource usage (CPU, memory, I/O, network).
  • Namespaces provide process, network, mounted points, and user isolation.

Main resource limitation parameters:

  • CPU:
    • --cpu-shares: Sets the relative "priority" of the container. The container gets a share of available CPU proportional to this value compared to other containers with --cpu-shares. Default is 1024.
    • --cpu-quota: Limits CPU usage with an absolute value in microseconds per --cpu-period. For example, --cpu-period=100000 --cpu-quota=50000 means 50% of one core.
    • --cpuset-cpus: Restricts the container to specific CPU cores (e.g., 0,1 or 0-3).
    • --cpuset-mems: Limits the container's access to specific NUMA memory nodes.
  • Memory:
    • --memory: Limits the amount of RAM available to the container. Supports suffixes b, k, m, g.
    • --memory-swap: Sets a limit on total memory (RAM + Swap). If less than --memory, the container cannot use swap. If --memory-swap is greater than --memory, the difference is the maximum available swap.
    • --memory-swappiness: Sets the swappiness coefficient for the container (default -1, which matches host settings).
    • --memory-reservation: Soft memory limit. The container will use at least this amount if available but can consume more up to --memory. The system tries to reserve this amount under memory pressure.
    • --kernel-memory: Limits the kernel memory used by the container.
  • I/O (Block IO):
    • --blkio-weight: Sets the relative weight for block I/O (default 500). Affects I/O bandwidth distribution.
    • --blkio-weight-device: Sets weight for a specific block device.
    • --device-read-bps / --device-write-bps: Limits read/write speed (bytes per second) for a specific device.
    • --device-read-iops / --device-write-iops: Limits read/write operations per second for a specific device.
  • Network: Indirect limitation through network interface configuration in network namespace or using OS-level tools (e.g., tc).

Example usage:

# Run a container with CPU limit (50% of one core) and memory (512MB)
docker run -d --name my_limited_app \
    --cpu-quota=50000 --cpu-period=100000 \
    --memory=512m \
    my_image:latest
# Run a container with CPU limited to cores 0 and 1, 1GB memory, and block weight of 700
docker run -d --name another_limited_app \
    --cpuset-cpus="0,1" \
    --memory=1g \
    --blkio-weight=700 \
    another_image:latest