Memory Optimization and Resource Reclamation in Docker
Docker containers, when left unconstrained, can consume excessive host memory and degrade system performance. Implementing resource limits and periodic maintenance procedures ensures stable cluster operations.
Resource Constraints
Apply hard memory limits during container initialization to prevent individual workloads from exhausting host resources. The following example restricts a container to 512 megabytes of RAM with a 1 gigabyte swap ceiling:
docker run -d \
--name api-gateway \
--memory="512m" \
--memory-swap="1g" \
--memory-reservation="256m" \
nginx:alpine
The --memory-reservation flag sets a soft limit that the container may exceed temporarily during traffic spikes, while --memory enforces an absolute cap.
Monitoring Allocation
Track real-time consumption across all running instances using formatted output for better readability:
docker stats --all \
--format "table {{.Container}} {{.Name}} {{.MemUsage}} {{.NetIO}}"
For automated alerting, parse the JSON stream programmatically:
docker stats --no-stream --format "{{json .}}" | \
jq -r 'select(.MemPerc | tonumber > 80) | .Name'
Cleanup Procedures
Remove unused objects that retain memory-mapped caches. Target specific resource types rather than performing aggressive system-wide purges:
# Remove stopped containers older than 24 hours
docker container prune --filter "until=24h" --force
# Delete dangling and unreferenced images
docker image prune --all --filter "until=168h" --force
# Clean build cache and network overlays
docker builder prune --force
For comprehensive reclamation including volume data:
docker system prune --volumes --force
Service Recycling
When the Docker daemon itself exhibits resident set growth, restart the runtime without disrupting configured networks:
sudo systemctl reload-or-restart docker.service
On systems using SysVinit:
sudo service docker restart
Swap Configuration
Enable suppplementary swap space temporari to relieve memory pressure during high-load scenarios. First, allocate a 2 gigabyte swap file using a block-sized write:
sudo dd if=/dev/zero of=/swap-temp bs=1M count=2048
sudo chmod 600 /swap-temp
sudo mkswap /swap-temp
sudo swapon /swap-temp
To remove the swap file after the workload completes (which forces pages back into physical memory or clears them):
sudo swapoff /swap-temp
sudo rm -f /swap-temp
Verify current swap utilization with:
free -h | awk '/^Swap/ {print "Usage: " $3 "/" $2}'