brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: docker run --memory-swap decides whether a container may use swap

Docker
~/tips/tip-docker-run-memory-swap

docker run -d --name app --memory=512m --memory-swap=512m example/app:1.0

Sets memory plus swap together for a container, or turns swap off for it completely.

--memory only sets half of a memory limit. The other half is --memory-swap, and its default surprised me when I read it: the container may use as much swap as RAM.

The resource constraints page explains that --memory-swap only works when --memory is set, and that it is the total of memory plus swap, not the swap alone. The docs give these cases:

  • --memory=300m --memory-swap=1g gives 300 MB of RAM and 700 MB of swap.
  • Setting it equal to --memory turns swap off for the container.
  • Unset, the container may use swap equal to --memory, so 600 MB in total for a 300 MB limit.
  • -1 allows unlimited swap, up to what the host has.
docker run -d --name app --memory=512m --memory-swap=512m example/app:1.0

That line gives the container 512 MB and no swap, so it hits its limit instead of slowing the whole machine while it swaps. I would pick this for anything where a slow container is worse than a restarted one.

When the limit is hit, by default the kernel kills processes inside the container that hits out-of-memory, and the container may exit. The docs also mention --oom-kill-disable, but they say to use it only together with -m, and I would leave it alone. The minimum for --memory is 6 MB, and swap limits only mean something if the host has swap at all.

Further reading: Resource constraints

More Docker tips ONBUILD RUN /usr/local/bin/python-build --dir /app/src SHELL ["/bin/bash", "-c"] docker commit <container> myname/testimage:version3 docker import /path/to/exampleimage.tgz docker compose events All Docker tips (192) All topics

Link