Scaling & Resources
Compose runs on one machine, but that machine can still run several copies of a service, and you can (and should) tell Docker how much CPU and memory each container may use. This lesson covers both: replicas on a single host, and resource limits and reservations. They use the same deploy: keys that Swarm uses across a cluster, so what you learn here carries straight over to Scaling Services and Reservations & Limits.
Replicas
Three ways to ask for more than one container of a service:
$ docker compose up -d --scale worker=4 # on the command line (overrides the file)
$ docker compose scale worker=4 # change a running projectservices:
worker:
deploy:
replicas: 4 # in the file (portable to Swarm)
# scale: 4 # the older Compose-only key, same effectUse one of the two keys, not both. Compose refuses contradicting values:
services:
worker:
image: ghcr.io/acme/api:3.1
command: ["celery", "-A", "app", "worker"]
scale: 3
deploy:
replicas: 2services.worker: can't set distinct values on 'scale' and 'deploy.replicas': invalid compose project
Replicas are numbered: demo-worker-1, demo-worker-2, … Scaling down removes the highest numbers first. Each replica gets its own IP, and the service name resolves to all of them (see Service Discovery & DNS).
What scales well, and what doesn't
| Service | Scale it? | Why |
|---|---|---|
| queue workers (Celery, Sidekiq, BullMQ) | yes, easily | they pull jobs; more workers = more throughput |
| stateless web/API behind a proxy | yes | the proxy spreads requests |
| a service that publishes a fixed host port | no, not as is | only one container can bind host port 8000 |
| database, Redis primary | no | replicas would each have their own data; use the database's own replication |
anything with container_name |
no | names must be unique |
The port problem
Two replicas can't both publish 8000:8000. Options:
- Don't publish the scaled service at all; put a reverse proxy in front (the usual answer).
- Publish only the container port (
"8000"), and Docker picks a free random host port per replica. - Publish a range with as many ports as replicas:
services:
web:
image: ghcr.io/acme/web:2.0
ports: ["8000-8002:8000"]
deploy:
replicas: 3name: demo
services:
web:
deploy:
replicas: 3
image: ghcr.io/acme/web:2.0
networks:
default: null
ports:
- mode: ingress
target: 8000
published: 8000-8002
protocol: tcp
networks:
default:
name: demo_default
Each replica takes the next free port of the range: 8000, 8001, 8002. It works, but clients now need to know three ports, which is why option 1 wins:
host :80
│
┌─────▼─────┐ round-robin over ┌─────────────┐
│ nginx │──── web:8000 ───────▶│ demo-web-1 │
│ (1 replica│ │ demo-web-2 │
│ publishes│ │ demo-web-3 │
│ :80) │ └─────────────┘
└───────────┘ (no published ports)Note that nginx resolves web once at startup by default; if you scale later, reload nginx or configure a resolver 127.0.0.11 valid=10s; with a variable in proxy_pass so it re-resolves. Traefik and Caddy discover containers dynamically.
Limits and reservations
services:
api:
image: ghcr.io/acme/api:3.1
deploy:
resources:
limits:
cpus: "0.50"
memory: 512M
pids: 200
reservations:
cpus: "0.25"
memory: 128Mname: demo
services:
api:
deploy:
resources:
limits:
cpus: 0.5
memory: "536870912"
pids: 200
reservations:
cpus: 0.25
memory: "134217728"
image: ghcr.io/acme/api:3.1
networks:
default: null
networks:
default:
name: demo_default
Compose normalised the values: "0.50" CPUs became the number 0.5, and 512M became the byte count 536870912 (512 × 1024 × 1024).
| Setting | Meaning on one host |
|---|---|
limits.memory |
hard cap; above it the kernel's OOM killer kills the process (exit 137) |
limits.cpus |
CPU time cap: 0.5 = half of one core on average, throttled beyond |
limits.pids |
maximum number of processes/threads, a guard against fork bombs |
reservations.memory |
soft guarantee: under memory pressure the container is reclaimed down to this |
reservations.cpus |
mostly a scheduling hint; on a single host it isn't enforced (Swarm uses it to place tasks) |
Older files use service-level keys (mem_limit, cpus, pids_limit); Compose still accepts them, but deploy.resources is the portable form. Don't mix both for the same setting.
How much does it fit?
Reservations are promises: the sum of what you reserve must fit on the host. A quick capacity check like the one Swarm's scheduler does per node:
host = {"cpus": 4.0, "memory_mb": 8192}
services = {
# replicas reserve cpu reserve MB limit MB
"api": (3, 0.25, 256, 512),
"worker": (4, 0.50, 512, 1024),
"db": (1, 1.00, 2048, 4096),
"redis": (1, 0.10, 256, 512),
}
cpu = sum(r * c for r, c, _, _ in services.values())
mem = sum(r * m for r, _, m, _ in services.values())
mem_limit = sum(r * l for r, _, _, l in services.values())
print(f"reserved cpus : {cpu:.2f} of {host['cpus']} -> {'ok' if cpu <= host['cpus'] else 'OVERCOMMITTED'}")
print(f"reserved memory: {mem} MB of {host['memory_mb']} -> {'ok' if mem <= host['memory_mb'] else 'OVERCOMMITTED'}")
print(f"sum of limits : {mem_limit} MB ({mem_limit / host['memory_mb']:.0%} of RAM, fine if not all peak at once)")
# how many workers fit if everything else stays?
free_cpu = host["cpus"] - (cpu - 4 * 0.50)
free_mem = host["memory_mb"] - (mem - 4 * 512)
print("max workers by cpu :", int(free_cpu // 0.50))
print("max workers by memory:", int(free_mem // 512))reserved cpus : 3.85 of 4.0 -> ok
reserved memory: 5120 MB of 8192 -> ok
sum of limits : 10240 MB (125% of RAM, fine if not all peak at once)
max workers by cpu : 4
max workers by memory: 10
Limits may add up to more than the host has (overcommit), as long as the services don't all hit their limits at the same moment. Reservations shouldn't.
Watching usage
$ docker compose stats --no-stream
NAME CPU % MEM USAGE / LIMIT MEM % NET I/O PIDS
demo-api-1 3.12% 141.2MiB / 512MiB 27.58% 1.2MB / 3.4MB 9
demo-api-2 2.87% 138.9MiB / 512MiB 27.13% 1.1MB / 3.1MB 9
demo-worker-1 48.40% 602.5MiB / 1GiB 58.84% 310kB / 280kB 5(sample output) Set limits from what you observe under realistic load, plus headroom: too tight and the OOM killer strikes during a traffic peak; too loose and one leaking service starves the rest.
When one host isn't enough
Compose scaling stops at the edge of one machine: no rescheduling if the host dies, no spreading across hosts, no rolling updates with health-gated rollback. That's the job of an orchestrator: Swarm keeps the same file format, Kubernetes adds autoscaling.
Learn more: Resource Limits · Compose in Production · Kubernetes Resources
Test yourself
Why can't a service with ports: ["8000:8000"] run 3 replicas?
- Compose limits replicas to 1
- Only one container can bind host port 8000
- DNS can't handle it
- deploy.replicas is Swarm-only
What happens when a container goes above limits.memory?
- It is throttled
- The kernel OOM killer kills it (exit code 137)
- Docker adds swap
- Nothing, limits are hints
What does docker compose config print for memory: 512M?
- 512M
- "536870912" (bytes)
- 0.5G
- 512