Skip to content

Lesson 10 of 24Real apps

Resource Limits, Restarts and Logging Drivers

What --memory and --cpus really do in the kernel, why containers die with 137 or slow down under load, how restarts behave, and where logs go.

18 min read0/4 questions

The API has run fine for a month. Then on a busy Monday it restarts every few hours, docker ps shows Up 12 minutes when it should say weeks, and p99 latency doubles even though the CPU graph never goes above 60%. Meanwhile the server's disk is 97% full, and nobody knows why. Each of these has the same root: the runtime settings you set once in Docker in Production (--memory, --cpus, "log to stdout") and never looked at again. This lesson goes underneath them, to the kernel features that enforce limits, the runtimes that ignore them, the restart loop, and the logging drivers that quietly fill disks.

Limits are cgroups

Namespaces control what a container can see. Control groups (cgroups) control what it can use. Every container gets its own cgroup, and the flags you pass to docker run are written into files in that cgroup. Modern Linux distributions use cgroups v2, one unified tree under /sys/fs/cgroup, and inside a container you see your own cgroup at that path.

Flagcgroup v2 fileExample value
--memory 512mmemory.max536870912
--memory-reservation 256mmemory.low268435456
--cpus 2cpu.max200000 100000
--cpu-shares 512cpu.weightscaled from shares
--pids-limit 200pids.max200

You can read them directly, which is often faster than finding the right docker inspect field:

docker exec api cat /sys/fs/cgroup/memory.max      # the limit in bytes, or "max"docker exec api cat /sys/fs/cgroup/memory.current  # usage now, including page cachedocker exec api cat /sys/fs/cgroup/memory.events   # oom and oom_kill countersdocker exec api cat /sys/fs/cgroup/cpu.stat        # nr_throttled, throttled_usec

The kernel enforces these limits. Docker only writes the numbers. That is why the same limits work the same way in Kubernetes and ECS: they write to the same files.

Memory: the limit, the OOM killer, and exit 137

--memory (or -m) sets a hard limit. When the processes in the cgroup try to use more, the kernel first tries to reclaim memory, mostly by dropping page cache (file data it was keeping around). If it cannot free enough, the OOM killer picks a process inside the cgroup and sends it SIGKILL. SIGKILL cannot be caught, so there is no traceback, no "shutting down" log line, nothing. The process exits with code 137 (128 + signal 9).

How a container gets OOM-killed
API process: allocatingAPI processallocatingcgroup: memory.max = 512Mcgroupmemory.max = 512Mpage cache: reclaimablepage cachereclaimableOOM killer: kernelOOM killerkernelDocker: records stateDockerrecords statecharge pagesreclaim firststill overSIGKILLoom event

Every page the process touches is charged to its cgroup. memory.current rises, and it includes page cache from files the app read or wrote.

1/5

Confirm it, do not guess it:

docker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' apidocker events --filter container=api --filter event=oom --since 24h

Three details separate people who have debugged this from people who have read about it:

  • 137 does not always mean OOM. docker stop sends SIGTERM and, if the app ignores it, SIGKILL after the timeout: also 137. docker kill too. Check OOMKilled before you blame memory.
  • The OOM killer may kill a child, not PID 1. With gunicorn or uvicorn running four workers, the killer usually picks the biggest worker. The master survives, logs something like "worker was sent SIGKILL, perhaps out of memory", and starts a new one. The container never exits, so there is no 137, only users seeing dropped requests and a counter going up in memory.events (oom_kill).
  • On a Mac, there are two limits. Docker Desktop runs a Linux VM with its own memory size. A container with no limit can still be killed when the whole VM runs out. Check Docker Desktop's resource settings when local builds or tests die for no reason.

The other memory flags:

  • --memory-reservation is a soft limit, below --memory. Under memory pressure on the host, the kernel tries to push containers back toward their reservation. It is a hint, not a guarantee, and does nothing without contention.
  • --memory-swap is memory plus swap. Set it equal to --memory to allow no swap, which most servers want: a container swapping is slower than one that restarts. Leave it unset and the container gets as much swap as memory, if the host has swap at all.
  • --oom-kill-disable exists. Do not use it without a memory limit, or one container can take the whole host down.

CPU: quotas, shares, and throttling

--cpus 2 does not reserve two cores. It sets a CFS quota: in every 100 ms period, the container's threads together may run for at most 200 ms of CPU time. Use the quota up early in the period and every thread in the container is throttled, paused, until the next period starts.

This is the hidden latency bug. An API with eight busy threads and --cpus 2 burns its 200 ms of quota in the first 25 ms of each period, then sits frozen for 75 ms. Average CPU use looks like a modest 2 cores, but a request that arrives during the frozen part waits up to 75 ms before any code runs. Run the model:

Pythoncfs_throttle.py
PERIOD_MS = 100 def simulate(cpus: float, busy_threads: int, periods: int = 10) -> None: quota_ms = cpus * PERIOD_MS throttled = 0 for _ in range(periods): demand_ms = busy_threads * PERIOD_MS # CPU time wanted this period if demand_ms > quota_ms: throttled += 1 run_ms = quota_ms / busy_threads # wall time until quota is gone frozen_ms = PERIOD_MS - run_ms if busy_threads * PERIOD_MS > quota_ms else 0 print(f"cpus={cpus} threads={busy_threads}: throttled {throttled}/{periods} periods, " f"runs {run_ms:.1f} ms then frozen {frozen_ms:.1f} ms") simulate(cpus=2, busy_threads=2)simulate(cpus=2, busy_threads=8)simulate(cpus=0.5, busy_threads=1)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

PERIOD_MS = 100
quota_ms = 1.0 * PERIOD_MS
threads = 4
run_ms = quota_ms / threads
print(run_ms, PERIOD_MS - run_ms)
Need a nudge? Hints walk you through it.

The fixes are to run fewer threads (match the worker count to the quota), raise the limit, or, on some platforms, set a CPU request without a hard limit. Watch the evidence in cpu.stat: if nr_throttled climbs steadily during traffic, you are being throttled.

Two other CPU flags behave differently:

  • --cpu-shares (default 1024, mapped to cpu.weight on cgroups v2) is a relative weight. It only matters when the host's CPUs are fully busy; then a container with 2048 gets twice the time of one with 1024. On an idle host it changes nothing. It never throttles.
  • --cpuset-cpus 0-3 pins the container to specific cores. Useful for latency-sensitive work and benchmarks, rarely needed for web apps.

Runtimes that do not read the limits

The kernel enforces limits, but your language runtime decides how many threads to start and how big a heap to grow. Many make that decision from the host's numbers.

Python worker counts. os.cpu_count() returns the number of CPUs on the host: 64 on a big server, even with --cpus 2. Python 3.13 added os.process_cpu_count(), which respects CPU affinity, so it follows --cpuset-cpus, but it does not read the CFS quota from --cpus. A config like workers = os.cpu_count() * 2 + 1 starts 129 workers in a 2-CPU, 1 GB container: throttling and an OOM kill. Read the quota yourself or, simpler, set the count explicitly from an environment variable. (PYTHON_CPU_COUNT overrides both functions in 3.13 and later.)

Pythoncpu_quota.py
import os def quota_cpus(cpu_max: str) -> float | None: quota, period = cpu_max.split() return None if quota == "max" else int(quota) / int(period) # What /sys/fs/cgroup/cpu.max holds for --cpus 2 and for no limitfor line in ["200000 100000", "max 100000"]: print(f"cpu.max={line!r} -> quota cpus: {quota_cpus(line)}") print("os.cpu_count() here:", os.cpu_count()) workers = int(os.environ.get("WEB_CONCURRENCY", "2"))print("workers from WEB_CONCURRENCY:", workers)
Output
Press Run (⌘ Enter) to see what happens.

Memory multiplies by workers. Each worker is a separate process with its own copy of your app. Four workers at 180 MB each, plus the master, need about 750 MB before a single large request. Size the limit from measured per-worker memory (docker stats under load) times the worker count, plus headroom.

Node.js sizes its default heap from available memory, and modern versions read the cgroup limit. The default may still not fit what else the process needs (buffers, native modules live outside the heap). Set --max-old-space-size (in MB, via NODE_OPTIONS) to about 75% of the container limit, and check the result with v8.getHeapStatistics().heap_size_limit.

The JVM has been container-aware for years, but by default only uses 25% of the limit for heap. Teams set -XX:MaxRAMPercentage=75 so a 2 GB container does not run a 512 MB heap.

Quick check
A FastAPI image starts gunicorn with workers = os.cpu_count() * 2 + 1. It runs with --cpus 2 --memory 1g on a 32-core host and is OOM-killed shortly after start. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

Small limits that bite

  • --pids-limit: caps the number of processes and threads. A fork bomb, or a bug that spawns a subprocess per request, then fails inside one container instead of exhausting the host's process table. Set it on anything that runs user-supplied code.
  • --ulimit nofile=65536:65536: the open file limit (soft:hard). Every socket is a file descriptor, so a proxy or WebSocket server holding thousands of connections hits "too many open files" at a low default.
  • --shm-size: /dev/shm defaults to 64 MB. Headless Chrome (Playwright, Puppeteer) uses shared memory for rendering and crashes with odd errors on busy pages; PostgreSQL uses it for parallel queries. Give them --shm-size 1g.

In Compose, the same settings are service keys:

compose.yaml
services:
  api:
    image: shop-api:1.4.2
    deploy:
      resources:
        limits: { memory: 1G, cpus: "2" }
        reservations: { memory: 512M }
    memswap_limit: 1G
    pids_limit: 256
    ulimits:
      nofile: { soft: 65536, hard: 65536 }
  e2e:
    image: mcr.microsoft.com/playwright:v1.48.0-noble
    shm_size: 1gb

The Playwright tag is only an example; use the version that matches your test package.

Restart policies and health

PolicyRestarts when
no (default)Never
on-failure[:N]The exit code is non-zero, at most N times if given
alwaysAlways; after a manual docker stop it waits until the daemon restarts
unless-stoppedLike always, but a manual stop is remembered even across daemon restarts

Docker does not restart instantly forever. It waits 100 ms before the first restart and doubles the delay each time, up to one minute. Once a container stays up for 10 seconds, the delay resets. docker ps shows Restarting (1) 4 seconds ago, and docker inspect -f '{{.RestartCount}}' api shows how many times it has gone round.

A crash loop hides the first error. The first failure might be a real cause (a migration failed halfway); every failure after it is a symptom (the app now trips over the half-applied migration). docker inspect only keeps the latest exit code, and if log rotation is tight, the earliest lines are gone. When you see a loop, read the logs from the start, not the tail, and consider on-failure:5 so it gives up and leaves evidence.

Healthchecks add a second state. A container with a HEALTHCHECK starts as starting, becomes healthy when a check passes, and becomes unhealthy after retries failures in a row (3 by default). Here is the trap: plain Docker does not restart an unhealthy container. It records the status and emits a health_status event, and Compose uses it for depends_on. Restarting on unhealthy is the job of an orchestrator: Swarm, ECS, and Kubernetes (through its own liveness probes) act on it.

Healthcheck states in plain Docker
startinghealthyunhealthyexitedcheck passesretries failretries failcheck passesonly if the app dies

currentwaitingdone

Every container with a healthcheck begins in starting. Failures during start-period do not count.

1/4

Logging drivers: where stdout goes

Your app writes to stdout and stderr. Docker hands those streams to a logging driver. The default is json-file, which appends every line, as JSON, to a file under /var/lib/docker/containers/<id>/. By default it never rotates. A chatty container running for months is the classic "disk full on a server where nothing changed" incident.

Fix it once for the whole host in /etc/docker/daemon.json, then restart the daemon:

/etc/docker/daemon.json
{
  "log-driver": "local",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  }
}

Two gotchas. The option values are strings ("3", not 3). And the change only applies to new containers; existing ones keep their old settings until they are recreated. The local driver is what Docker's docs recommend: it rotates by default and stores logs in a compact format. Keep json-file with max-size only if some tool reads those files directly.

In Compose you can set it per service, and a YAML anchor keeps it in one place:

compose.yaml
x-logging: &default-logging
  driver: local
  options:
    max-size: "10m"
    max-file: "3"
 
services:
  api:
    logging: *default-logging
  worker:
    logging: *default-logging

Other drivers send logs off the host: awslogs (CloudWatch), gcplogs, fluentd, syslog, journald, splunk, gelf. docker logs can read json-file, local, and journald directly; for remote drivers, Docker Engine keeps a small local cache (dual logging) so docker logs still works. In production, many teams leave the driver at local and run a collector (Fluent Bit, Vector, the Datadog or CloudWatch agent) that tails the files, which keeps the app decoupled from the log backend.

Two more decisions matter at scale:

  • Blocking vs non-blocking. By default, delivery is blocking: if the driver cannot keep up (a slow remote endpoint), your app's print calls block. Setting mode: non-blocking with a max-buffer-size keeps the app fast but drops lines when the buffer is full. Choose based on whether losing logs or stalling requests is worse.
  • Structure. Write one JSON object per line ({"level": "error", "msg": "...", "request_id": "..."}). Every backend can then filter by field instead of grepping text, as the Python Backend course covers in its logging lesson.
Match the pairs0/5 matched

Match each symptom to its most likely cause.

Choose an item, then its match on the other side.

Watching usage

docker stats --no-stream            # CPU %, memory used / limit, PIDs, per containerdocker system df -v                 # disk used by images, containers, volumes, build cachedocker inspect -f '{{.LogPath}}' api   # the json-file log on disk for one container

docker stats memory includes some page cache, so a container sitting near its limit is not necessarily in trouble. Watch the trend under load, and check memory.events for oom_kill counts. CPU % above 100 means more than one core (200% = two full cores).

Put it in order4 steps

A container keeps exiting with 137. Put the investigation in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
cgroup
A kernel feature that limits and accounts for the CPU, memory, and processes a group of processes can use. Every container gets one.
OOM killer
The kernel mechanism that SIGKILLs a process when a cgroup cannot stay under its memory limit.
CFS quota
The CPU time a container may use per period (100 ms by default). --cpus 2 means 200 ms per period.
CPU throttling
Pausing a container's threads after its quota runs out for the period. Shows as nr_throttled in cpu.stat.
restart policy
no, on-failure[:N], always, or unless-stopped: when Docker restarts an exited container, with doubling backoff.
logging driver
Where Docker sends a container's stdout and stderr: json-file (default), local, awslogs, fluentd, and others.
dual logging
A local cache Docker keeps so docker logs works even when the driver ships logs elsewhere.