Data
DataIntermediate

MongoDB in Docker for Production: Replica Sets, WiredTiger, Auth & Backups

How to run MongoDB in Docker for production without OOM kills or broken transactions: Replica Set setup, WiredTiger cache sizing, oplog, keyFile auth, and backups.

Cover image: MongoDB in Docker for Production: Replica Sets, WiredTiger, Auth & Backups
Contents

Running MongoDB in Docker takes ten seconds in a local tutorial—and one unexpected traffic spike to trigger an OOMKill (exit 137) or broken multi-document writes in production.

Most outages with containerized MongoDB come down to five defaults: running standalone without a Replica Set, letting WiredTiger and aggregation pipelines collide inside an untuned memory limit, forgetting --keyFile when turning on auth, leaving Docker’s 10-second SIGKILL timeout in place, and exposing 27017 or Mongo Express on 0.0.0.0.

The production checklist. Pin mongo:8.0.x, initialize a single-node Replica Set (rs0) with a keyFile, cap --wiredTigerCacheSizeGB at 50% of container RAM, size --oplogSize explicitly, set stop_grace_period: 60s, bind mongo-express to 127.0.0.1, and back up with mongodump --oplog.

Production MongoDB in Docker Compose architecture showing Replica Set rs0, WiredTiger 50% cache cap, keyFile auth, localhost-only Mongo Express, and oplog backups
A production Docker Compose layout isolates admin access on 127.0.0.1, bounds WiredTiger memory, and streams consistent --oplog backups off-host.

Why standalone docker run mongo breaks in production

If you launch docker run -d mongo without --replSet, MongoDB boots in standalone mode. That silently disables three features modern backends rely on:

  • Multi-document ACID transactions: any session.withTransaction() call throws an error (Transaction numbers are only allowed on a replica set member or mongos).
  • Change Streams: event-driven workers and CDC pipelines (watch()) require an oplog, which only exists in a Replica Set.
  • Zero-downtime scaling later: converting a busy standalone container into a Replica Set requires a maintenance restart, whereas a single-node Replica Set (rs0) lets you attach secondaries live with rs.add().

Sizing WiredTiger Cache and Container Memory

Inside Docker, WiredTiger does not own all of your container’s RAM. Even if you set deploy.resources.limits.memory: 8G, WiredTiger needs headroom for the Linux filesystem page cache (where compressed data pages live), per-connection thread stacks, MongoDB 8.0 parallel oplog applier buffers, and in-memory sorts (100 MB default cap per stage).

Container RAM allocation for MongoDB 8.0: 50% WiredTiger cache vs OS filesystem page cache vs connections and OOMKill risk
Reserve 50% of the container limit for WiredTiger and 50% for OS page cache, connections, and aggregation buffers to avoid OOMKill (exit 137).

Use this straightforward sizing rule in production:

Sizing WiredTiger Cache and Container Memory
Container RAM Limit --wiredTigerCacheSizeGB Remaining RAM (Page Cache + Connections + Sorts) Recommended Workload
2 GB 0.75 – 1 ~1 – 1.25 GB Small internal tools / dev staging
4 GB 2 ~2 GB Light production APIs (< 50 GB hot set)
8 GB 4 ~4 GB Standard production services
16 GB+ 8 – 10 ~6 – 8 GB High-concurrency & heavy aggregations

Sizing the Oplog explicitly

In MongoDB 8.0, the default oplog (local.oplog.rs) takes 5% of free disk space (minimum 990 MB). On a 500 GB cloud volume, that wastes 25 GB on a tiny database; on a tight 20 GB volume, a 990 MB oplog can roll over during a heavy batch import before a backup or secondary catches up.

Pass --oplogSize in megabytes explicitly (for example --oplogSize=4096 for 4 GB) so your retention window covers 24–48 hours of peak writes.

Production compose.yaml (MongoDB 8.0 + Replica Set + Auth + Mongo Express)

Before starting the stack, generate the keyFile required for internal Replica Set authentication. Note that the official mongo image runs mongod as UID/GID 999:

Terminal window
mkdir -p ./mongo-secrets
openssl rand -base64 756 > ./mongo-secrets/mongo-keyfile
chmod 400 ./mongo-secrets/mongo-keyfile
sudo chown 999:999 ./mongo-secrets/mongo-keyfile

Now pin the exact MongoDB 8.0 patch version and put every production safeguard into compose.yaml:

compose.yaml
services:
mongodb:
image: mongo:8.0.3
container_name: mongodb-prod
restart: unless-stopped
stop_grace_period: 60s
command:
- "mongod"
- "--replSet=rs0"
- "--keyFile=/etc/mongo/keyfile"
- "--bind_ip_all"
- "--wiredTigerCacheSizeGB=4"
- "--oplogSize=4096"
environment:
MONGO_INITDB_ROOT_USERNAME: ${MONGO_ROOT_USER}
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_ROOT_PASS}
ports:
- "127.0.0.1:27017:27017"
volumes:
- mongo_data:/data/db
- mongo_config:/data/configdb
- ./mongo-secrets/mongo-keyfile:/etc/mongo/keyfile:ro
ulimits:
nofile:
soft: 64000
hard: 64000
nproc:
soft: 32000
hard: 32000
deploy:
resources:
limits:
memory: 8G
reservations:
memory: 4G
healthcheck:
test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
mongo-express:
image: mongo-express:1.0.2
container_name: mongo-express-admin
restart: unless-stopped
depends_on:
mongodb:
condition: service_healthy
ports:
- "127.0.0.1:8081:8081"
environment:
ME_CONFIG_MONGODB_URL: "mongodb://${MONGO_ROOT_USER}:${MONGO_ROOT_PASS}@mongodb:27017/?authSource=admin"
ME_CONFIG_BASICAUTH: "true"
ME_CONFIG_BASICAUTH_USERNAME: ${ME_USER}
ME_CONFIG_BASICAUTH_PASSWORD: ${ME_PASS}
volumes:
mongo_data:
mongo_config:

Initialize the Replica Set and create an app user

Once mongodb-prod reports healthy, initialize rs0 once:

Terminal window
docker exec -it mongodb-prod mongosh -u "$MONGO_ROOT_USER" -p "$MONGO_ROOT_PASS" --authenticationDatabase admin --eval '
rs.initiate({
_id: "rs0",
members: [{ _id: 0, host: "mongodb:27017" }]
})'

Never let your application connect with the root user. Create a least-privilege application user scoped only to its target database (readWrite):

// Run inside mongosh as root
use app_prod
db.createUser({
user: "app_service",
pwd: "REPLACE_WITH_STRONG_PASSWORD",
roles: [{ role: "readWrite", db: "app_prod" }]
})

Then configure your application with an explicit Replica Set connection string (replicaSet=rs0, authSource=app_prod, retryWrites=true, w=majority):

mongodb://app_service:REPLACE_WITH_STRONG_PASSWORD@mongodb:27017/app_prod?replicaSet=rs0&authSource=app_prod&retryWrites=true&w=majority

Named Volumes, ulimits, and Graceful Shutdown

Three host-level settings decide whether MongoDB survives restarts and traffic bursts:

  • Use Docker named volumes on local NVMe/SSD: Never place /data/db on NFS, SMB, or macOS/Windows host bind mounts. WiredTiger relies on POSIX fsync guarantees and direct file locking; network shares risk silent corruption, and macOS VirtioFS/osxfs bind mounts cripple random I/O.
  • Raise nofile (64000) and nproc (32000): WiredTiger opens a file descriptor per collection and per index file, plus one socket per client connection. Under Docker’s default low limits, mongod fails with Too many open files during traffic spikes.
  • Set stop_grace_period: 60s: Docker’s default docker stop waits only 10 seconds before sending SIGKILL. If WiredTiger is flushing a large checkpoint, SIGKILL forces crash recovery from journal files on the next boot.

Monitoring WiredTiger Cache and Oplog Window

Before an OOMKill or replication stall happens, two built-in mongosh checks tell you whether your container budget is healthy:

// 1. Check WiredTiger cache pressure (bytes currently in cache vs configured max)
const wt = db.serverStatus().wiredTiger.cache;
print({
usedGB: (wt["bytes currently in the cache"] / 1e9).toFixed(2),
maxGB: (wt["maximum bytes configured"] / 1e9).toFixed(2),
dirtyPct: ((wt["tracked dirty bytes in the cache"] / wt["maximum bytes configured"]) * 100).toFixed(1)
});
// 2. Verify oplog retention window (aim for 24–48h+)
rs.printReplicationInfo();

If dirtyPct consistently stays above 20% or docker stats shows container memory climbing past 85%, either reduce --wiredTigerCacheSizeGB slightly or upgrade the container RAM limit.

Backups without downtime (--oplog)

Never back up a live MongoDB container by copying or tarring /data/db—WiredTiger files are actively mutated in memory and on disk, producing a corrupt snapshot.

Because your container runs as a Replica Set, mongodump --oplog captures all writes that occur while the dump is running so the archive restores to a consistent point in time:

Terminal window
docker exec mongodb-prod mongodump \
--username="$MONGO_ROOT_USER" \
--password="$MONGO_ROOT_PASS" \
--authenticationDatabase=admin \
--oplog \
--gzip \
--archive > "mongo-backup-$(date -u +%Y%m%dT%H%M%SZ).archive.gz"

Ship the encrypted .archive.gz off-host (for example to S3 or Cloudflare R2) with a retention policy, and test mongorestore --oplogReplay --gzip --archive=... into a disposable container every month.

Read next: Running relational workloads alongside MongoDB? See our PostgreSQL in Docker for Production guide for PGDATA volume paths, shm_size, and PgBouncer pooling.

The Bottom Line

Containerized MongoDB is rock-solid in production once you stop treating it like a throwaway local container:

  1. Boot with --replSet=rs0 and --keyFile from day one so transactions, Change Streams, and future secondaries work cleanly.
  2. Cap --wiredTigerCacheSizeGB at 50% of container memory, set --oplogSize explicitly, and raise stop_grace_period: 60s + nofile limits.
  3. Keep 27017 and mongo-express bound to 127.0.0.1, create a scoped readWrite app user, and run scheduled mongodump --oplog backups off-host.

Frequently asked questions

Why do I need a Replica Set for MongoDB in Docker if I only have one server?

MongoDB disables multi-document ACID transactions, Change Streams, and retryable writes on standalone instances. Initializing a single-node Replica Set (--replSet rs0 + rs.initiate()) unlocks all of those features immediately and lets you add secondaries later without downtime.

How should I size wiredTigerCacheSizeGB inside a Docker container?

Set --wiredTigerCacheSizeGB to roughly 50% of the container's hard memory limit (for example, 4 GB on an 8 GB container). The remaining RAM is critical for the OS filesystem page cache (compressed data on disk), connection threads, aggregation pipelines, and MongoDB 8.0 parallel replication buffers.

Why does MongoDB fail to start with --replSet and root credentials?

Once authentication is active, every replica set member must authenticate internally using either a shared keyFile or x.509 certificates. Create a random 756-byte keyFile with chmod 400 and chown 999:999, mount it into /etc/mongo/keyfile, and pass --keyFile /etc/mongo/keyfile.

Is mongo-express safe to run in production?

Only if bound strictly to 127.0.0.1 (or an internal VPN/Tailscale interface) and never exposed directly on 0.0.0.0:8081. For routine ad-hoc queries, connecting MongoDB Compass over an SSH tunnel is even safer because zero admin web UI stays running permanently.

How do I back up MongoDB in Docker without stopping the container?

Never tar /data/db while mongod is running. Because your container runs as a Replica Set, run mongodump --oplog --archive --gzip via docker exec or a sidecar cron job to capture a point-in-time consistent snapshot, and upload the encrypted archive off-host (such as S3 or Cloudflare R2).

From the community

Discussion on Mastodon & Bluesky

Replies to this article from the open web, pulled in live. No ads, no tracking scripts.

Loading replies …
Reply on MastodonReply on Bluesky

Reply there — it shows up here automatically.

ENDE