0
0
DockerHow-ToBeginner · 3 min read

How to Limit Container Memory in Docker

To limit container memory in Docker, use the --memory option with docker run to set the maximum memory the container can use. For example, docker run --memory=500m limits the container to 500 megabytes of RAM.
📐

Syntax

The --memory option sets the maximum amount of memory a container can use. You specify it with a size suffix like m for megabytes or g for gigabytes.

Example parts:

  • docker run: command to start a container
  • --memory=500m: limits memory to 500 megabytes
  • image_name: the container image to run
bash
docker run --memory=500m image_name
💻

Example

This example runs an nginx container limited to 200 megabytes of memory. It shows how to apply the memory limit when starting a container.

bash
docker run --memory=200m --name limited-nginx -d nginx

docker stats limited-nginx --no-stream
Output
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS xxxxxxxxxxxx limited-nginx 0.00% 5.5MiB / 200MiB 2.75% 1.2kB / 0B 0B / 0B 2
⚠️

Common Pitfalls

Common mistakes when limiting container memory include:

  • Not specifying a unit (like m or g), which causes an error.
  • Setting the limit too low, causing the container to be killed if it exceeds memory.
  • Forgetting to monitor container memory usage after setting limits.

Always use units and monitor your containers to avoid unexpected stops.

bash
docker run --memory=500 image_name  # Wrong: missing unit

docker run --memory=500m image_name  # Correct: with unit
📊

Quick Reference

OptionDescriptionExample
--memorySet max memory for container--memory=300m
--memory-swapSet total memory + swap limit--memory-swap=1g
--memory-reservationSoft limit for memory usage--memory-reservation=200m

Key Takeaways

Use the --memory option with units (m or g) to limit container RAM.
Always specify a unit to avoid errors when setting memory limits.
Set realistic memory limits to prevent container crashes.
Monitor container memory usage with docker stats after applying limits.
Use --memory-swap and --memory-reservation for advanced memory control.