In a production environment, one misbehaving container could consume all host resources, crashing other services. Docker allows you to set strict limits on CPU and Memory.
1. Setting Resource Limits
Memory Limits
You can set a hard limit (--memory) and a soft limit (--memory-reservation).
Action:
# Start a container with a 512MB limit
docker run -d --name limited-nginx --memory="512m" nginxResult:
f5e6d7c8b9a0...CPU Limits
You can specify how many "shares" or a percentage of a CPU a container can use.
Action:
# Limit the container to 0.5 (50%) of one CPU core
docker run -d --name cpu-limited --cpus="0.5" nginxResult:
a1b2c3d4e5f6...2. Monitoring Container Performance
Docker provides built-in tools to see how your containers are behaving in real-time.
Live Statistics
Action:
docker stats --no-streamResult:
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
f5e6d7c8b9a0 limited-nginx 0.00% 2.34MiB / 512MiB 0.46% 1.02kB / 0B 0B / 0B 2
a1b2c3d4e5f6 cpu-limited 0.00% 2.31MiB / 15.63GiB 0.01% 1.02kB / 0B 0B / 0B 23. Handling Crashes (Restart Policies)
Docker can automatically restart your container if it crashes or the host reboots.
| Policy | Description |
|---|---|
no | Do not restart (Default). |
on-failure | Restart only if the container exits with a non-zero code. |
always | Always restart, regardless of the exit code. |
unless-stopped | Similar to always, but doesn't restart on host boot if it was manually stopped. |
Action:
docker run -d --name auto-restart --restart unless-stopped nginxSummary
- Always set limits in production to prevent "noisy neighbors."
- Use
docker statsto monitor real-time resource usage. - Use Restart Policies to keep your applications highly available.