| |

Docker 38 🐳 Container Resource Allocations: CPU Shares, CPU Quotas (–cpus), and Memory Limits (–memory)

⏱️ Estimated read: 15 min | |

A container without resource limits is a container that can consume the entire host. A runaway process inside a container can starve every other container, exhaust the host’s memory, and trigger the kernel’s OOM killer, which may terminate processes outside the container as well. Docker’s resource allocation controls exist to prevent this. They set boundaries on how much CPU and memory a container can use, ensuring that one container’s misbehavior does not become the host’s problem.

The controls fall into two categories: CPU and memory. CPU controls come in two flavors. CPU shares (--cpu-shares) are a relative weight used only during contention — they do not limit CPU usage when the host is idle. CPU quotas (--cpus, --cpu-quota/--cpu-period) are hard limits that cap the container’s CPU time regardless of contention. Memory controls are similar: --memory is a hard limit, and --memory-reservation is a soft limit that only activates under memory pressure. The distinction between soft and hard limits is fundamental to how the kernel enforces these constraints.

This chapter covers three areas. First, why resource allocations exist — the noisy-neighbor problem, the OOM killer, and the cost of unbounded containers. Second, how CPU controls work — CPU shares, the CFS scheduler, --cpus, and the relationship between --cpu-quota and --cpu-period. Third, how memory controls work — hard limits, soft limits, swap, and the OOM killer’s behavior. The chapter ends with a complete example session, a quick reference, best practices, common pitfalls, real-world examples, and diagrams showing the resource control mechanisms.

Key point: CPU shares are a relative weight enforced only under contention. CPU quotas (--cpus) are a hard cap on CPU time. Memory limits (--memory) are a hard cap on memory usage; exceeding it triggers the OOM killer. Memory reservations are a soft limit that only activates under host memory pressure. All of these are enforced by Linux cgroups .


Why resource allocations exist

The noisy-neighbor problem. Without resource limits, a single container can consume all available CPU and memory. A container running a CPU-intensive build can starve every other container on the host. A container with a memory leak can consume all available RAM, forcing the kernel to swap aggressively or invoke the OOM killer. The result is that one container’s behavior affects every other container’s performance. Resource limits isolate containers from each other, ensuring that each gets a fair share of the host’s resources .

The OOM killer problem. When the host runs out of memory, the Linux kernel’s OOM killer selects processes to terminate. The selection is based on an OOM score, and by default, any process is subject to being killed — including Docker itself and other critical system processes. Docker mitigates this by adjusting the OOM priority so that containers are more likely to be killed than the Docker daemon, but the risk remains. Setting an explicit memory limit on each container ensures that a container that exceeds its limit is killed by the cgroup OOM killer, not the host-level OOM killer. The container dies, but the host survives .

The resource-visibility problem. A container without a memory limit sees the host’s total memory when it queries /proc/meminfo or similar interfaces. A Java application, for example, may size its heap based on the host’s available RAM rather than the container’s actual limit. Setting an explicit limit changes what the container sees, allowing applications to size their internal buffers and heaps appropriately .

The cost of unbounded containers. An unbounded container is a latent risk. It may run fine for months and then, under an unexpected load spike or a memory leak, consume resources that other containers need. The incident is often sudden and difficult to diagnose because the container’s resource usage was never bounded. Setting limits at creation time makes the container’s resource footprint predictable and the failure mode explicit .

The trade-off. Resource limits introduce complexity. Setting a limit too low causes the container to be throttled or killed when it legitimately needs more resources. Setting it too high defeats the purpose of the limit. The correct value depends on the application’s actual resource requirements, which must be measured rather than guessed. Over-committing the host (setting limits that sum to more than the host has) is possible with CPU shares but not with hard CPU quotas or memory limits. The trade-off is between the safety of explicit limits and the operational effort of tuning them.


a. CPU shares — relative weight

CPU shares define the relative priority of a container when competing for CPU time. The default is 1024 shares per container. The shares are not a limit; they are a weight that determines how CPU time is divided when multiple containers are contending for the same CPU .

docker run -d --cpu-shares=512 nginx
docker run -d --cpu-shares=2048 nginx

If both containers are running CPU-intensive workloads, the second container receives approximately four times more CPU time than the first (2048 vs 512). If only one container is running, it can use the entire CPU regardless of its share value. The shares only matter when there is contention .

The shares are enforced by the CFS (Completely Fair Scheduler). The kernel allocates CPU time proportionally to the shares. A container with 512 shares and another with 1024 shares, both busy, will receive CPU time in a 1:2 ratio .

CPU shares are a soft limit. They do not prevent a container from using more CPU when the host is idle. They only determine the allocation when the host is busy.


b. CPU quotas — hard limits with --cpus and --cpu-quota

For hard limits, Docker provides the --cpus flag and the lower-level --cpu-quota/--cpu-period pair.

--cpus specifies the number of CPUs the container can use. It accepts fractional values:

docker run -d --cpus="1.5" nginx

The container is limited to 1.5 CPU cores worth of CPU time. If the host has multiple CPUs, the container’s processes may run on different cores, but the total CPU time consumed per scheduling period is capped at 1.5 cores .

--cpus is a convenience wrapper around the CFS quota mechanism. It is equivalent to setting --cpu-period=100000 and --cpu-quota=150000 (150,000 microseconds of CPU time per 100,000-microsecond period, which is 1.5 cores) .

The underlying parameters are:

  • --cpu-period: The CFS scheduling period in microseconds. Default is 100,000 (100ms). Most users do not change this .
  • --cpu-quota: The maximum CPU time the container can use within one period, in microseconds. A quota of -1 means no limit .

A container with --cpu-period=100000 --cpu-quota=25000 gets 25,000 microseconds of CPU time per 100,000-microsecond period, which is 25% of one CPU core .

The difference between CPU shares and CPU quotas is the difference between relative priority and absolute cap. Shares determine how CPU time is divided when there is contention. Quotas determine the maximum CPU time the container can use, regardless of contention.


c. Memory limits — hard and soft

Docker enforces memory limits through cgroups. The primary control is --memory (or -m), which sets a hard limit on the container’s memory usage .

docker run -d --memory="512m" nginx

The container cannot use more than 512 megabytes of memory. If it tries, the cgroup OOM killer terminates processes inside the container. The container exits with code 137 (128 + 9, indicating SIGKILL) .

--memory-reservation sets a soft limit. It is only enforced when the host is under memory pressure or contention. If the host has plenty of free memory, the container can exceed its reservation. If the host is low on memory, the kernel reclaims memory from containers that exceed their reservation .

docker run -d --memory="1g" --memory-reservation="512m" nginx

The container has a hard limit of 1GB and a soft limit of 512MB. Under normal conditions, it can use up to 1GB. Under memory pressure, the kernel tries to keep it at or below 512MB.

--memory-swap controls swap usage. It only has meaning if --memory is also set. The value of --memory-swap is the total memory plus swap. If --memory="300m" and --memory-swap="1g", the container can use 300MB of RAM and 700MB of swap .

To disable swap entirely, set --memory-swap equal to --memory:

docker run -d --memory="512m" --memory-swap="512m" nginx

This is the recommended configuration for predictable performance, as swap usage can cause significant latency .


Complete Example Session

# ============================================
# PART 1: CPU SHARES — RELATIVE WEIGHT
# ============================================

# Two containers, different shares.
# When both are busy, CPU time is divided 1:4.

docker run -d --name cpu-low --cpu-shares=256 nginx
docker run -d --name cpu-high --cpu-shares=1024 nginx

# cpu-high gets approximately 4x the CPU time of cpu-low
# when both are running CPU-intensive workloads.


# ============================================
# PART 2: CPU SHARES DO NOT LIMIT IDLE USAGE
# ============================================

# If cpu-low is the only busy container, it can
# use the entire CPU despite its low share value.

# Shares only matter under contention.


# ============================================
# PART 3: --CPUS — HARD LIMIT
# ============================================

# Limit the container to 1.5 CPU cores.

docker run -d --name cpu-limited --cpus="1.5" nginx

# The container can never use more than 1.5 cores
# of CPU time, regardless of how many cores the
# host has or how idle the host is.


# ============================================
# PART 4: --CPU-QUOTA AND --CPU-PERIOD
# ============================================

# The underlying mechanism behind --cpus.

docker run -d --name cpu-quota \
  --cpu-period=100000 \
  --cpu-quota=50000 \
  nginx

# 50,000us quota / 100,000us period = 0.5 cores = 50% of one CPU.


# ============================================
# PART 5: CPU SET — PIN TO SPECIFIC CORES
# ============================================

# Bind the container to specific CPU cores.

docker run -d --name cpu-pinned --cpuset-cpus="0,3" nginx

# The container's processes only run on cores 0 and 3.


# ============================================
# PART 6: MEMORY HARD LIMIT
# ============================================

# Set a hard memory limit of 512MB.

docker run -d --name mem-limited --memory="512m" nginx

# If the container exceeds 512MB, the OOM killer
# terminates its processes. Exit code 137.


# ============================================
# PART 7: MEMORY SOFT LIMIT
# ============================================

# Set a soft limit that activates under pressure.

docker run -d --name mem-soft \
  --memory="1g" \
  --memory-reservation="512m" \
  nginx

# The container can use up to 1GB normally.
# Under memory pressure, the kernel tries to
# keep it at or below 512MB.


# ============================================
# PART 8: DISABLE SWAP
# ============================================

# Set swap equal to memory to disable swap.

docker run -d --name no-swap \
  --memory="512m" \
  --memory-swap="512m" \
  nginx

# The container cannot use any swap.


# ============================================
# PART 9: UPDATE LIMITS ON A RUNNING CONTAINER
# ============================================

# docker update changes limits without recreating.

docker update --cpus="2" --memory="1g" --memory-swap="1g" mycontainer


# ============================================
# PART 10: VERIFYING LIMITS
# ============================================

# Check the container's current limits.

docker inspect -f '{{.HostConfig.NanoCpus}}' mycontainer
# Nanoseconds of CPU per second (1e9 = 1 CPU)

docker inspect -f '{{.HostConfig.Memory}}' mycontainer
# Memory limit in bytes

docker inspect -f '{{.State.OOMKilled}}' mycontainer
# true if killed by OOM

# Live resource usage:
docker stats mycontainer --no-stream

The ten parts show CPU shares, the contention-only behavior, --cpus, --cpu-quota/--cpu-period, CPU sets, memory hard limits, memory soft limits, swap disabling, docker update, and verification.


Quick Reference

CPU Controls

FlagTypeEffect
--cpu-sharesSoft (relative)Weight during contention; default 1024
--cpusHard (absolute)Max CPU cores; accepts decimals
--cpu-quotaHard (absolute)Max CPU microseconds per period
--cpu-periodHard (absolute)CFS period in microseconds; default 100000
--cpuset-cpusHard (binding)Pin to specific cores

Memory Controls

FlagTypeEffect
--memoryHardMax memory; OOM kill if exceeded
--memory-reservationSoftActivated under host memory pressure
--memory-swapHardTotal memory + swap; set equal to --memory to disable swap
--oom-kill-disable—Disable OOM killer; requires --memory

Verification Commands

CommandPurpose
docker stats <container>Live CPU/memory usage
docker inspect -f '{{.HostConfig.Memory}}'Memory limit in bytes
docker inspect -f '{{.HostConfig.NanoCpus}}'CPU limit in nanocores
docker inspect -f '{{.State.OOMKilled}}'Whether OOM killed
docker update --cpus --memoryUpdate limits on running container

CPU Shares vs Quotas

AspectSharesQuotas (--cpus)
EnforcementOnly under contentionAlways
LimitNone when idleHard cap
ValueRelative weightAbsolute cores
Use casePriority between containersGuaranteed maximum

Best Practices

✅ Do This:

# Use --cpus for hard CPU limits
docker run --cpus="1.5" myapp                                              # ✅
# Set memory limits on every production container
docker run --memory="512m" --memory-swap="512m" myapp                      # ✅
# Measure before setting limits
docker stats myapp --no-stream                                             # ✅
# Disable swap for predictable latency
--memory="512m" --memory-swap="512m"                                       # ✅
# Use docker update for live adjustments
docker update --memory="1g" myapp                                          # ✅

❌ Don’t Do This:

# Don't rely on CPU shares as a limit
--cpu-shares=512  # does not cap CPU when idle                          # ❌
# Don't set memory limits without measuring
--memory="64m"  # may kill the container immediately                      # ❌
# Don't use --oom-kill-disable without --memory
--oom-kill-disable  # dangerous without memory limit                      # ❌
# Don't over-commit memory limits
# sum of all --memory > host RAM → OOM risk                               # ❌
# Don't forget that --memory-swap only works with --memory
--memory-swap="1g"  # ignored without --memory                            # ❌

Common Pitfalls

PitfallWhy It HappensFix
Container killed with exit 137Exceeded memory limitIncrease --memory or fix the leak
CPU shares have no effectNo contention on the hostUse --cpus for hard limits
--memory-swap ignored--memory not setSet --memory alongside --memory-swap
Container uses host memory infoNo memory limit setSet --memory to change container’s view
OOM killer kills host processNo container memory limitSet --memory on every container
docker update memory failsSwap limit constraintUpdate --memory-swap first or together

Real-World Examples

1. CPU Shares for Priority

docker run --cpu-shares=2048 high-priority-app

2. Hard CPU Limit

docker run --cpus="0.5" low-priority-app

3. Memory Limit with Swap Disabled

docker run --memory="1g" --memory-swap="1g" app

4. Memory Reservation

docker run --memory="2g" --memory-reservation="1g" app

5. CPU Pinning

docker run --cpuset-cpus="0,1" app

6. Update Running Container

docker update --cpus="2" --memory="2g" app

7. Check OOM Status

docker inspect -f '{{.State.OOMKilled}}' app

8. Live Stats

docker stats app --no-stream

9. Compose Resource Limits

deploy:
  resources:
    limits:
      cpus: '1.5'
      memory: 512M

10. Java Heap with Container Limit

docker run --memory="2g" -e JAVA_OPTS="-Xmx1536m" app

Visual

CPU Shares vs CPU Quotas

┌──────────────────────────────────────────────────────────────┐
│  CPU SHARES vs CPU QUOTAS                                    │
│                                                              │
│  CPU SHARES (--cpu-shares):                                  │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Host is IDLE:                                       │    │
│  │    Container A (256 shares) → uses 100% CPU          │    │
│  │    Container B (1024 shares) → not running           │    │
│  │                                                       │    │
│  │  Host is CONTENDED:                                  │    │
│  │    Container A (256 shares)  → 20% CPU               │    │
│  │    Container B (1024 shares) → 80% CPU               │    │
│  │                                                       │    │
│  │  Shares are a WEIGHT, not a cap.                     │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  CPU QUOTAS (--cpus):                                        │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Host is IDLE:                                       │    │
│  │    Container A (--cpus=0.5) → max 50% CPU            │    │
│  │                                                       │    │
│  │  Host is CONTENDED:                                  │    │
│  │    Container A (--cpus=0.5) → max 50% CPU            │    │
│  │                                                       │    │
│  │  Quotas are a HARD CAP.                              │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Memory Hard Limit and OOM

┌──────────────────────────────────────────────────────────────┐
│  MEMORY HARD LIMIT                                           │
│                                                              │
│  --memory="512m"                                             │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Container memory usage:                             │    │
│  │                                                       │    │
│  │  0MB ──────────────── 512MB ────────────────►        │    │
│  │  │                     │                             │    │
│  │  │  normal operation   │  limit reached              │    │
│  │  │                     │                             │    │
│  │  │                     ▼                             │    │
│  │  │              OOM killer activates                 │    │
│  │  │              SIGKILL (exit 137)                   │    │
│  │  │              container dies                       │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  --memory-reservation="256m"                                 │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Under host memory pressure:                         │    │
│  │    kernel reclaims memory from containers            │    │
│  │    that exceed their reservation                     │    │
│  │                                                       │    │
│  │  Without pressure, container can use up to 512m      │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

CFS Quota Mechanism

┌──────────────────────────────────────────────────────────────┐
│  CFS QUOTA MECHANISM                                         │
│                                                              │
│  --cpu-period=100000 (100ms)                                 │
│  --cpu-quota=50000 (50ms)                                    │
│                                                              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  Period 1 (100ms):                                   │    │
│  │  [========== 50ms ==========][--- idle 50ms ---]     │    │
│  │                                                       │    │
│  │  Period 2 (100ms):                                   │    │
│  │  [========== 50ms ==========][--- idle 50ms ---]     │    │
│  │                                                       │    │
│  │  Period 3 (100ms):                                   │    │
│  │  [========== 50ms ==========][--- idle 50ms ---]     │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  50ms / 100ms = 0.5 cores = 50% of one CPU.                  │
│                                                              │
│  --cpus="0.5" is equivalent to this configuration.           │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Resource Verification

┌──────────────────────────────────────────────────────────────┐
│  VERIFYING LIMITS                                            │
│                                                              │
│  docker inspect -f '{{.HostConfig.NanoCpus}}' app            │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  1500000000  → 1.5 CPUs (nanoCPUs)                   │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  docker inspect -f '{{.HostConfig.Memory}}' app              │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  536870912  → 512 MB (bytes)                         │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  docker stats app --no-stream                                │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  NAME  CPU %  MEM USAGE / LIMIT   MEM %              │    │
│  │  app   45.2%  256MiB / 512MiB     50.00%             │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
│  docker inspect -f '{{.State.OOMKilled}}' app                │
│  ┌──────────────────────────────────────────────────────┐    │
│  │  false  → container was not OOM killed               │    │
│  └──────────────────────────────────────────────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
--cpu-sharesRelative weight (default 1024); only enforced under contention
--cpusHard limit on CPU cores; accepts decimals
--cpu-quota/--cpu-periodCFS quota mechanism behind --cpus
--cpuset-cpusPin container to specific CPU cores
--memoryHard memory limit; OOM kill if exceeded
--memory-reservationSoft limit; activated under host memory pressure
--memory-swapTotal memory + swap; set equal to --memory to disable swap
OOM killExit code 137; OOMKilled: true in inspect
docker updateChange limits on a running container

Key takeaways:

  • CPU shares are a relative weight, not a limit. They determine how CPU time is divided when containers contend for the same CPU. When the host is idle, a container with low shares can still use the entire CPU. Use --cpus for a hard limit .
  • --cpus is a hard cap on CPU time. It is equivalent to setting --cpu-quota and --cpu-period. A value of 1.5 means the container can use at most 1.5 CPU cores worth of CPU time per scheduling period, regardless of how many cores the host has .
  • --memory is a hard limit. If the container exceeds it, the cgroup OOM killer terminates its processes. The container exits with code 137, and docker inspect shows OOMKilled: true .
  • --memory-reservation is a soft limit. It only activates when the host is under memory pressure. Under normal conditions, the container can use up to --memory. Under pressure, the kernel tries to keep it at or below the reservation .
  • --memory-swap controls swap usage. It only has meaning if --memory is set. To disable swap entirely, set --memory-swap equal to --memory. This is recommended for predictable latency .
  • The OOM killer can kill host processes if no container limit is set. A container without a memory limit can consume all host memory, and the host-level OOM killer may terminate processes outside the container, including Docker itself. Setting --memory on every container ensures that only the container is killed .
  • Resource limits are enforced by Linux cgroups. Docker does not implement the limits itself; it configures cgroups, and the kernel enforces them. The limit values must be measured for the application, not guessed .
  • docker update changes limits on a running container. Not all limits can be changed without recreating the container, but CPU and memory limits generally can be updated. Memory limit updates may require updating the swap limit at the same time .

Remember: Resource allocations are the boundary between a container and its host. CPU shares determine priority under contention; CPU quotas determine the hard cap on CPU time. Memory limits determine when the OOM killer activates; memory reservations determine behavior under host pressure. Without limits, a container is unbounded, and its failure mode is the host’s failure. With limits, the container’s resource footprint is predictable, and its failure is contained. The correct limit values come from measurement, not guesswork — docker stats shows actual usage, and the limit should be set above the normal peak with headroom for unexpected load. The limits are enforced by the kernel through cgroups, and Docker’s role is to configure them. Once configured, they are the contract between the container and the host: the container gets no more than this, and the host is protected from the container.


Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!