Docker Compose — Resource Limits
Set CPU and memory limits to prevent any single container from consuming all host resources.
Deploy Resources (Compose v2)
services:
api:
image: myapi:latest
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.25"
memory: 128M
Limits vs Reservations
| Setting | Purpose |
|---|---|
limits |
Maximum a container can use (hard cap) |
reservations |
Minimum guaranteed to the container |
Host: 4 CPUs, 8 GB RAM
api: limits: 1 CPU, 512M reservations: 0.25 CPU, 128M
worker: limits: 2 CPU, 1G reservations: 0.5 CPU, 256M
db: limits: 2 CPU, 2G reservations: 1 CPU, 512M
Memory Units
| Unit | Meaning |
|---|---|
b |
Bytes |
k |
Kilobytes |
m |
Megabytes |
g |
Gigabytes |
512M |
512 megabytes |
1G |
1 gigabyte |
CPU Values
| Value | Meaning |
|---|---|
"0.5" |
Half a CPU core |
"1.0" |
One full CPU core |
"2.0" |
Two CPU cores |
"0.25" |
Quarter of a core |
Out of Memory (OOM)
When a container exceeds its memory limit, Docker kills it:
docker compose logs api | grep -i "killed"
myapp-api-1 | Killed
Combine with restart: unless-stopped to auto-recover:
services:
api:
image: myapi:latest
restart: unless-stopped
deploy:
resources:
limits:
memory: 512M
Monitor Resource Usage
docker stats
CONTAINER CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
myapp-api-1 2.5% 128MiB / 512MiB 25% 1.2MB / 500kB 0B / 4MB
myapp-db-1 1.0% 256MiB / 2GiB 12.5% 500kB / 300kB 10MB / 50MB
Production Template
services:
api:
image: myapi:latest
restart: unless-stopped
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.25"
memory: 128M
db:
image: postgres:16
restart: unless-stopped
deploy:
resources:
limits:
cpus: "2.0"
memory: 2G
reservations:
cpus: "0.5"
memory: 512M
shm_size: 256m
Summary
| Setting | Example | Purpose |
|---|---|---|
| CPU limit | cpus: "1.0" |
Max 1 core |
| Memory limit | memory: 512M |
Max 512 MB |
| CPU reservation | cpus: "0.25" |
Guaranteed 0.25 cores |
| Memory reservation | memory: 128M |
Guaranteed 128 MB |
| Monitor | docker stats |
Real-time usage |
Quick Reference
| Item | Detail |
|---|---|
| limits | Maximum resources (hard cap) |
| reservations | Guaranteed minimum resources |
| cpus | CPU cores (e.g. 1.0 = one core) |
| memory | RAM limit (e.g. 512M, 1G) |
| docker stats | Monitor live resource usage |
| OOM | Container killed if exceeds memory limit |