Q: How do you set resource limits for a Docker Compose service?
To set resource limits for a Docker Compose service, add deploy.resources.limits with cpus and memory to the service in compose.yaml. Docker Compose v2 applies these on docker compose up, while reservations declare a minimum.
Want to master this scenario in a live sandbox? KodeKloud's Docker Certified Associate (DCA) Hands-On Lab Course covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: To <strong>set resource limits for a Docker Compose service</strong>, add <code>deploy.resources.limits</code> with <code>cpus</code> and <code>memory</code> to the service in <code>compose.yaml</code>. Docker Compose v2 applies these on <code>docker compose up</code>, while reservations declare a minimum. Interviewers ask this to test whether you know the Compose Specification syntax, how limits behave at runtime (CPU throttling versus memory OOM kills), and how to verify enforcement. Mentioning the older <code>mem_limit</code> style shows you can read legacy files.
Mental model: limits, reservations and what they do
Compose maps these keys to the same cgroup controls as docker run flags. Remember that limits protect the host and neighbouring services, so a missing limit on one container is a risk to every other container on that machine.
- limits.cpus: a hard cap in CPU units, for example
"0.5"is half a core, enforced by CFS throttling. - limits.memory: a hard cap. If the process exceeds it the kernel OOM killer terminates it and Docker reports exit code 137.
- reservations: a soft minimum used for scheduling in Swarm. On a single host, a memory reservation acts as a soft limit under memory pressure.
- Legacy keys:
mem_limit,cpus,mem_reservationandpids_limitat service level are still supported by the Compose Specification. - Where it is enforced: limits are applied by the Docker Engine through cgroups on the host running the container, so they work the same in a laptop or a single-server deployment as they do for plain
docker run.
Hands-on: set resource limits for a Docker Compose service
A complete example with CPU, memory and process limits.
services:
api:
image: registry.example.com/my-api:2.0
deploy:
resources:
limits:
cpus: "0.50"
memory: 512M
reservations:
cpus: "0.25"
memory: 256M
pids_limit: 200
worker:
image: registry.example.com/my-worker:2.0
cpus: 1.0 # legacy-style service-level keys
mem_limit: 1g
- Quote CPU values: write
cpus: "0.50"as a string for portability. - Apply: run
docker compose up -d. Changing limits recreates the container. - Preview the merged config:
docker compose configshows what Compose will actually apply. - Swap and PIDs:
memswap_limitandpids_limitat the service level cap swap use and fork bombs. - Memory plus swap: by default a memory limit may allow equal swap on some hosts, which delays OOM kills but slows the app badly. Set
memswap_limitequal to the memory limit to disable extra swap.
Verify the limits are enforced
Confirm what Docker applied, not only what the file says.
docker compose up -d
docker compose config | grep -A4 limits
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'
# NAME CPU % MEM USAGE / LIMIT
# app-api-1 0.4% 120MiB / 512MiB
docker inspect --format '{{.HostConfig.NanoCpus}}' app-api-1
- Live usage:
docker stats --no-streamshows MEM USAGE / LIMIT, which should read 512MiB forapi. - Inspect HostConfig:
docker inspect --format '{{.HostConfig.Memory}} {{.HostConfig.NanoCpus}}' <container>prints bytes and nano-CPUs, here536870912 500000000. - OOM check:
docker inspect --format '{{.State.OOMKilled}} {{.State.ExitCode}}' <container>returnstrue 137after a memory kill. - Stress test: run a memory hog in a staging container to see the kill behaviour before production does.
- Docker Desktop: containers share the resources assigned to the Desktop VM, so a service limit above the VM allocation is meaningless. Raise the VM memory in settings first.
Failure modes and version caveats
Most surprises come from syntax history and runtime semantics. Check each symptom against the evidence before changing anything.
- Compose v1 and the deploy key: old
docker-compose1.x ignoreddeployoutside Swarm unless run with--compatibility. Compose v2 (docker compose) honours it. - Silent OOM kills: a container restarting every few minutes with exit code 137 is usually hitting its memory limit. Raise it or fix the leak.
- Runtime awareness: JVM, Node and Go may size heaps from host memory. Set JVM flags such as
-XX:MaxRAMPercentageso the heap fits inside the cgroup limit. - Throttled latency: a tight CPU cap throttles bursts. Check for slow requests when CPU looks low.
- Sizing method: run a realistic load test, record peak working set, and set the limit with headroom while keeping the reservation near typical usage.
Production practice: defaults and observability
Make sizing a measured, reviewed decision.
- Measure first: base limits on observed peak usage from
docker statsor cAdvisor with headroom, not guesses. - Use extension fields: define common limits once with a YAML anchor under an
x-key and reuse it in services. - Alert: track memory near limit, OOMKilled events and CPU throttling in Prometheus.
- Orchestrators: in Kubernetes translate these to
resources.requestsandresources.limitsin the pod spec. - Profiles per environment: keep dev with generous limits in an override file such as
compose.override.yamland enforce stricter production values incompose.prod.yaml.
- I set <code>deploy.resources.limits</code> with cpus and memory in the Compose file, plus reservations, and apply it with <code>docker compose up -d</code>.
- I confirm with <code>docker compose config</code>, <code>docker stats</code> and <code>docker inspect</code> for HostConfig.Memory and OOMKilled.
- I size from measured peaks, align runtime heap settings with the limit and alert on OOM kills and CPU throttling.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Relying on deploy limits with Compose v1 The legacy docker-compose 1.x ignored deploy outside Swarm, so containers ran unlimited. Use Compose v2.
- Setting memory limits below the runtime's heap needs The JVM or Node may try to exceed the cgroup limit and get OOM killed, even though the host has plenty of RAM.
- Unquoted or wrong CPU units cpus is a fraction of cores, not a percentage, so 50 means fifty cores. Use a quoted decimal like "0.5".
- Never checking exit codes Exit 137 with OOMKilled true is the only clear sign that limits killed the process. Without checking it, restarts look like random crashes.