Docker Compose Resource Limits: Practical Guide for Stable Containers
When running multiple containers on a single host—especially in embedded or resource-constrained environments—a single misbehaving service can degrade the entire system. Properly configuring resource constraints in Docker Compose ensures predictable performance and system stability.
⚙️ Core Configuration: Limits vs. Reservations #
The deploy.resources section defines how much CPU and memory a container can use—and how much it is guaranteed to receive.
| Feature | limits (Ceiling) |
reservations (Floor) |
|---|---|---|
| Purpose | Prevents excessive resource usage | Guarantees minimum resources |
| CPU | Caps CPU usage | Limited support outside Swarm |
| Memory | Enforced hard limit (OOM if exceeded) | Ensures availability at scheduling time |
Example (Compose V3.x) #
services:
app:
image: my-app:latest
deploy:
resources:
limits:
cpus: '0.50' # Max 50% of one CPU core
memory: 512M # Hard memory limit
reservations:
memory: 128M # Guaranteed minimum
🧠 The Compatibility Trap (Standalone vs Swarm) #
The deploy key was originally designed for Docker Swarm. In standalone Docker Compose, these settings may be ignored unless explicitly enabled.
Enable Compatibility Mode #
docker-compose --compatibility up -d
Compose V2 Note #
If you’re using the modern docker compose (without the hyphen), resource constraints may work natively depending on your Docker Engine version. Always verify behavior in your environment.
📊 Verification & Monitoring #
Setting limits is only half the job—you must confirm they are enforced.
Real-Time Monitoring #
docker stats
Snapshot Mode #
docker stats --no-stream
Pay attention to the MEM USAGE / LIMIT column:
- Example:
120MiB / 512MiB - Confirms your memory ceiling is active
🛠️ Best Practices for Stability #
1. Avoid Over-Provisioning #
Total memory reservations should never exceed host capacity. Otherwise, containers may fail to start.
2. Leave System Headroom #
Reserve at least 10–15% of system resources for:
- OS processes
- Docker daemon
- Background services
3. Tune Gradually #
Start with:
- High limits
- Low reservations
Then refine based on actual usage metrics.
4. Monitor Before Optimizing #
Use docker stats over time to:
- Identify memory leaks
- Detect CPU spikes
- Adjust limits based on real workloads
🚀 Summary #
Docker Compose resource constraints are essential for building predictable, stable systems:
- Limits protect the host from runaway containers
- Reservations ensure critical services always have resources
- Monitoring validates your configuration
In constrained environments, this isn’t optional—it’s the difference between a stable system and a cascading failure.