Docker MongoDB Terminates When It Runs Out of Memory
Running MongoDB inside a Docker container works fine in isolation, but when multiple services share the same host and memory is constrained, MongoDB's aggressive caching behaviour can consume all available RAM and cause the container to be killed by the OOM killer.
The fix is straightforward once you understand how MongoDB manages memory.
Why MongoDB Uses So Much Memory
Since version 3.2, MongoDB uses the WiredTiger storage engine by default. WiredTiger maintains an internal cache to keep frequently accessed data in memory, accelerating reads and writes. By default, this cache is sized at 50% of available RAM minus 1 GB — which in a constrained Docker environment means it can easily compete with every other service on the host.
When the host runs low on memory, the Linux kernel's OOM killer terminates the process consuming the most, which is typically MongoDB. The container then exits unexpectedly.
The Solution: Limit the WiredTiger Cache
WiredTiger exposes a configuration parameter, --wiredTigerCacheSizeGB, that caps the internal cache size regardless of how much RAM is available. Setting this to a value appropriate for your environment prevents MongoDB from starving other containers.
Docker Run
docker run -d \
--name mongodb \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongo --wiredTigerCacheSizeGB 0.25
Docker Compose
version: '3.8'
services:
mongodb:
image: mongo:5
command: ["--wiredTigerCacheSizeGB", "0.25"]
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password
ports:
- "27017:27017"
Choosing a Cache Size
There is no universal value — it depends on your workload and how much RAM your host has available. A few guidelines:
- For development or low-traffic containers,
0.25GB is usually sufficient. - For production containers with dedicated resources, aim for 50% of the memory you have allocated to that container.
- The minimum value MongoDB accepts is
0.25GB.
WiredTiger also uses filesystem cache on top of its internal cache. The OS will still cache data through the page cache, so restricting the internal cache does not eliminate caching entirely — it simply gives the OS more control over memory allocation.
Verify It Is Working
Connect to the running container and check the current cache configuration:
docker exec -it mongodb mongosh -u admin -p password --eval \
"db.serverStatus().wiredTiger.cache['maximum bytes configured']"
The output is in bytes — divide by 1073741824 to convert to GB and confirm it matches your configured limit.
Conclusion
MongoDB's default memory behaviour is optimised for dedicated servers, not shared Docker environments. Setting --wiredTigerCacheSizeGB to an appropriate value gives you stable, predictable memory usage and prevents the container from being killed under load. It is a one-line change with a significant impact on reliability.