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 usingdocker-compose upfor 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
memoryare typically found under deploy.resources.limits in Compose file version 3 and later,memswap_limit(andmem_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_limitandmemswap_limitdirectly at the service level. In version 3 and later,mem_limitwas replaced by deploy.resources.limits.memory, butmemswap_limitremained 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:

memswap_limit and memory to the same value.Important Notes:
- memswap_limit requires memory:
memswap_limitis a modifier attribute that only has meaning ifmemory(ormem_limitin older versions) is also set. - Compatibility Mode (--compatibility): If you are using an older Compose file (e.g., v2) with
mem_limitandmemswap_limitdirectly under the service, and want to deploy it as a stack withdocker stack deploy, you might need to use the --compatibility flag withdocker-composeto translate these older syntax elements into the deploy.resources format. However, formemswap_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, definingmemswap_limitat 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).