Table of Contents
- Linux Memory Allocation
- Docker’s Default Memory Behavior
- Setting a Hard RAM Limit with
--memory - Controlling Swap with
--memory-swap - Memory Flags Comparison
- Best Practices
- References
Linux Memory Allocation
A typical Linux host provides:- Physical RAM (e.g., 2 GB, 4 GB, 8 GB)
- Swap space: disk-backed extension of RAM
Docker’s Default Memory Behavior
Without explicit flags, Docker containers can use all host memory (RAM + swap). This can lead to a single container consuming all resources and destabilizing the host.Always set memory limits in production to avoid unexpected OOM kills on the host.
Setting a Hard RAM Limit with --memory
Use --memory (or -m) to cap a container’s physical RAM usage. Specify a value with a suffix:
- B (bytes)
- K (kilobytes)
- M (megabytes)
- G (gigabytes)
Exceeding the
--memory limit results in an immediate container termination. Monitor your application’s memory usage with tools like docker stats.Controlling Swap with --memory-swap
By default, setting only --memory allows unlimited swap usage (up to the host’s swap). To enforce a combined RAM+swap limit, use --memory-swap. The value you provide is the total memory budget:
- Total limit =
--memory+ (--memory-swap−--memory)
Common Swap Configurations
-
Disable swap entirely
Set both flags to the same value:Here, swap available = 512 MB − 512 MB = 0 MB. -
Allocate specific swap
Allow 256 MB swap on top of 512 MB RAM:Here, swap available = 768 MB − 512 MB = 256 MB.
Memory Flags Comparison
| Flag | Purpose | Example |
|---|---|---|
--memory | Hard cap on container’s physical RAM | --memory=512m |
--memory-swap | Total RAM + swap limit (must be ≥ --memory) | --memory=512m --memory-swap=768m |
--memory-swappiness | Kernel swap tendency (0–100) | --memory-swappiness=10 |
Best Practices
- Always set both
--memoryand--memory-swapin production. - Use monitoring (e.g.,
cAdvisor, Prometheus) to track container memory. - Tune
--memory-swappinessto control how aggressively a container uses swap. - Test under load to identify realistic memory requirements.