Sobes.tech
Middle

How is resource limitation organized in Docker?

sobes.tech AI

Answer from AI

Resource limitations in Docker are implemented using Cgroups (Control groups), a Linux kernel mechanism that allows organizing processes into hierarchical groups and allocating system resources (CPU, RAM, I/O, network bandwidth) among them.

Main types of limitations:

  • CPU:
    • cpu_shares: Sets a relative weight for CPU access. If resources are available, the container can use more than its share.
    • cpu_quota / cpu_period: Define strict limits on CPU usage. cpu_period sets the period of time (in microseconds), and cpu_quota is the maximum microseconds of CPU the container can use during this period.
    • cpuset_cpus: Specifies which CPU cores the container's process is allowed to run on.
    • cpuset_mems: Specifies from which NUMA nodes memory can be used.
  • Memory:
    • memory: Sets a strict limit on the amount of RAM available to the container. If exceeded, processes may be terminated by the kernel (OOM Killer).
    • memory_swap: Defines the limit on total RAM and swap memory.
    • memory_swappiness: Configures how aggressively the kernel will swap out container memory pages.
  • Block I/O:
    • blkio_weight: Sets a relative weight for block device (disk) access.
    • blkio_read_bps / blkio_write_bps: Limit the read/write speed to/from block devices in bytes per second.
    • blkio_read_iops / blkio_write_iops: Limit the number of read/write IOPS to/from block devices.
  • Network:
    • Network bandwidth limitations are not directly implemented by Docker's built-in Cgroups. Usually, host-level tools like tc (traffic control) or third-party solutions are used.

Docker uses flags in the docker run command to set these limitations, which are then translated into corresponding Cgroup parameters in the filesystem /sys/fs/cgroup/.

Examples of flags:

# Limit memory to 512MB and CPU to 50% of one core (if period = 100ms, quota = 50ms)
docker run -m 512m --cpu-quota=50000 --cpu-period=100000 <image>

# Limit usage to CPU cores 0 and 1
docker run --cpuset-cpus="0,1" <image>

# Limit write speed to block device /dev/sda to 10MB/s
docker run --device-write-bps /dev/sda:10MB <image>