Docker in ProductionLesson 5.3
Docker resource limits and preventing container sprawl
--memory, --cpus, --memory-swap, cgroup limits, docker stats, resource starvation, OOM killer, resource reservation in Compose
Preventing a Runaway Container From Killing Your Host
Without limits, any container can consume all available host memory or CPU, starving other containers and the host OS. Always set limits in production.
Setting Limits at Runtime
# Limit to 512MB RAM and 0.5 CPU cores
docker run -d \
--memory=512m \
--cpus=0.5 \
--memory-swap=512m \
my-app
Setting --memory-swap equal to --memory disables swap, preventing the container from swapping to disk when it hits the memory ceiling. Instead, the Linux OOM killer terminates the container process — which is usually preferable to uncontrolled swap usage.
Monitoring Resource Usage
# Live resource stats for all running containers
docker stats
# One-time snapshot, no-stream
docker stats --no-stream
Limits in Docker Compose
services:
api:
deploy:
resources:
limits:
cpus: "0.5"
memory: 512M
reservations:
memory: 256Mreservations guarantee a minimum amount of resources; limits set the maximum. Compose deploy resource limits apply when using docker compose with the --compatibility flag or Docker Swarm.
