---
title: "MongoDB in Docker for Production: Replica Sets, WiredTiger, Auth & Backups"
description: "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."
author: Aleksei Aleinikov
date: 2026-11-26
lang: en
tags: [mongodb docker, mongodb on docker, mongodb docker compose, mongo express docker, wiredtiger cache size, mongodb replica set docker, mongodb production backup]
canonical: https://www.alekseialeinikov.com/en/blog/topics/data/mongodb-in-docker-production
source: alekseialeinikov.com
---

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

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`.

> [!NOTE]
> **MongoDB in Production Series — Part 1.** This guide covers containerizing MongoDB safely for production: Replica Set initialization, WiredTiger memory limits, `keyFile` auth, and consistent backups.

> [!KEY]
> **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](https://media.alekseialeinikov.com/data/mongodb-in-docker/architecture-1200.29a9763dd53de3e0.webp "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](https://media.alekseialeinikov.com/data/mongodb-in-docker/memory-traps-1200.9d9716098e6ed580.webp "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:

| 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`:

```bash
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`:

```yaml title="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:
```

> [!WARNING]
> **Never expose `27017` or `mongo-express` (`8081`) on `0.0.0.0`.** Binding to `127.0.0.1` keeps both unreachable from the public internet—open them from your laptop only over an SSH tunnel (`ssh -L 8081:127.0.0.1:8081 user@server`) or private VPN. Note also that `chown 999:999` + `chmod 400` on a bind-mounted `keyfile` works natively on Linux hosts; on macOS/Windows Docker Desktop, copy the keyfile into the `mongo_config` named volume (`/data/configdb/mongo-keyfile`) via an init step so file permissions stay strict.

### Initialize the Replica Set and create an app user

Once `mongodb-prod` reports healthy, initialize `rs0` once:

```bash
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`):

```javascript
// 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`):

```text
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:

```javascript
// 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:

```bash
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](https://www.alekseialeinikov.com/en/blog/topics/data/postgresql-in-docker-production) 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.
