Proper resource management on a server is critical — not only to handle workloads efficiently, but also to limit the blast radius of a cyberattack. When deploying containers, you can assign and cap CPU and RAM usage per container.
In your docker-compose.yml files, you can define both limits and reservations for each service:
- reservations = guarantee a minimum amount of resources for a container
- limits = prevent a container from exceeding a given amount of resources
Add the following block to your docker-compose.yml for each service you want to constrain:
services:
my-service:
deploy:
resources:
limits:
cpus: "0.15"
memory: 128m
reservations:
cpus: "0.05"
memory: 64MYou can use any combination:
- limits only
- reservations only
- both limits and reservations
The CPU limit (cpus: "0.15") means the container can use at most 15% of a single CPU core on the host. Other CPU scheduling options exist (e.g. cpu_shares, cpu_quota), but in most cases letting the OS and kernel handle scheduling is the right call.
Running the stack#
Once your .yml file is ready, start your containers with:
# Docker Compose v2 (recommended, built into Docker)
docker compose up -dNote: Since Docker Compose v2, the
deploy.resourcesblock is supported natively without any extra flags. If you are still using Docker Compose v1 (the standalonedocker-composebinary), you need to add--compatibilityto enable this block outside of Swarm mode.
To monitor resource usage in real time, run:
docker statsThe Memory column will reflect the limits and reservations defined in your compose file. CPU limits are enforced by the kernel but are not directly shown in docker stats.