If you search "docker compose memory swap limit" on google, it will return incorrect information and if you configured your compose file according to what it says to do and run docker compose up you'll get an error.
Here are the incorrect instructions you'll see:

The issue of defining memory-swap with deploy.resources.limits in Docker Compose arises from the way resource limits are handled in different Compose file versions and deployment scenarios.

Understanding the Problem:

  • Deploy section and Swarm: The deploy section in a Docker Compose file, including deploy.resources.limits, is primarily designed for use with Docker Swarm deployments (when using docker stack deploy). When using docker-compose up for single-host deployments, the deploy section is largely ignored, except for certain elements like secrets or configs in some versions.
  • memswap_limit location: While other memory limits like memory are typically found under deploy.resources.limits in Compose file version 3 and later, memswap_limit (and mem_swappiness) is historically defined at the service level, directly under the service name, not within the deploy section. This difference in placement can lead to confusion.
  • Compose File Versions: Older Compose file versions (like version 2.x) allowed defining mem_limit and memswap_limit directly at the service level. In version 3 and later, mem_limit was replaced by deploy.resources.limits.memory, but memswap_limit remained at the service level.

Solution:

To define memory-swap in Docker Compose, ensure you are using a recent version of Docker Compose (v2 or later, which aligns with the Compose Specification), and place the memswap_limit directly under the service definition, alongside other service-level configurations.

Example:

💡
TIP: To prevent your container from using any host swap memory at all, set the memswap_limit and memory to the same value.

Important Notes:

  • memswap_limit requires memory: memswap_limit is a modifier attribute that only has meaning if memory (or mem_limit in older versions) is also set.
  • Compatibility Mode (--compatibility): If you are using an older Compose file (e.g., v2) with mem_limit and memswap_limit directly under the service, and want to deploy it as a stack with docker stack deploy, you might need to use the --compatibility flag with docker-compose to translate these older syntax elements into the deploy.resources format. However, for memswap_limit, it is still best to define it at the service level.
  • Docker Swarm vs. docker-compose up: Remember that deploy.resources.limits is primarily for Swarm. If you are using docker-compose up, defining memswap_limit at the service level is the correct approach. 

If you have any questions/comments regarding this article, click here or scroll down below (login isn't required to post comments and there's no waiting period).