In this lesson, you will learn how to prevent a single runaway container from hogging all the hardware resources by setting explicit limits on CPU and memory.
The Problem: The "Noisy Neighbor"
In a multi-container environment, Docker containers share the host machine’s resources by default. If one container suddenly spikes in usage—perhaps due to a memory leak or an intensive data processing task—it can starve other containers, causing your entire application stack to crash or become unresponsive. This is known as the "noisy neighbor" problem.
Defining Constraints
To maintain stability, you define deploy constraints within your docker-compose.yml file. By setting limits, you tell the Docker engine exactly how much capacity a service is allowed to consume.
- Memory: You can specify a
limit(the maximum memory the container can use) and areservation(the minimum amount of memory the engine guarantees for that container). - CPU: You can cap the CPU usage as a percentage of the host's total processing power.
Here is how you apply these constraints in a docker-compose.yml file:
services:
web-app:
image: my-app:latest
deploy:
resources:
limits:
cpus: '0.50' # Use at most 50% of one CPU
memory: 512M # Use at most 512MB of RAM
reservations:
memory: 128M # Reserve 128MB of RAM upfront
Why This Matters
When you set these constraints, the container runtime actively monitors usage. If a container attempts to exceed its memory limit, the operating system may kill the process to protect the host. While this sounds harsh, it is a crucial safety mechanism in production. By reserving resources, you ensure that critical services (like your database) always have the baseline power they need to function, while setting limits ensures that less critical services cannot cause a system-wide outage if they misbehave.
Key Takeaway: By defining explicit CPU and memory constraints, you transform your multi-container environment from a competitive free-for-all into a stable, predictable system where resources are reserved for what matters most.