FALVARIX
FALVARIX
devops --real --no-hype

MongoDB on Docker: Replica Sets, Auth and Backups

MongoDB on Docker: Replica Sets, Auth and Backups

MongoDB on Docker: Replica Sets, Auth and Backups

There’s a line that shows up in post-mortems all over the world: “the database was in a container and nobody remembered the volume.” Spinning up MongoDB with a simple docker run takes thirty seconds. The hard part is making that container survive a reboot, a full disk, an unauthorized access and a docker compose down -v run in a hurry.

In this guide we’ll set up MongoDB on Docker with production-grade practices. You’ll get a three-node replica set, keyfile authentication, persistent data and automated backups, with a restore you’ve actually tested.

Why MongoDB on Docker (and when not to)

Docker gives you reproducibility. The same compose.yaml spins up the environment on your laptop, in staging and on a VPS, and that cuts down on surprises. For small and mid-sized teams, a containerized replica set across several hosts is a solid, cost-effective option.

It’s worth being honest about the limits:

  • A single host isn’t real high availability. Three containers on the same machine protect you from a crashed process, not from hardware failure. To tolerate losing a server, spread the nodes across different hosts.
  • Critical data demands storage discipline. If you don’t control the underlying disk (type, IOPS, snapshots), consider a managed service like MongoDB Atlas.
  • Official images are the foundation. Always use the official image and pin the version (mongo:7.0), never latest.

If you already work with containers every day, this fits naturally. And if your application images are still too heavy, you’ll want this guide on Docker multi-stage builds in production.

Architecture: a three-node replica set

A replica set has a primary that accepts writes and secondaries that replicate the oplog. If the primary goes down, the remaining members elect a new one in seconds. You need a majority to elect, which is why an odd number matters: with three nodes you tolerate one going down.

Our topology:

  • mongo1, mongo2, mongo3: members of the rs0 replica set.
  • An internal Docker network with no ports published to the internet.
  • A named volume per node for the data.
  • An ephemeral container that initializes the replica set.
  • A backup service that runs mongodump on a schedule.

Generate the keyfile

In a replica set with authentication, the nodes authenticate to each other using a shared keyfile. Generate it once:

mkdir -p mongo && cd mongo
openssl rand -base64 756 > mongo-keyfile
chmod 400 mongo-keyfile
sudo chown 999:999 mongo-keyfile

UID 999 is the mongodb user inside the official image. If the permissions are looser than they should be, mongod refuses to start, and rightly so. Never commit this file to Git.

The compose.yaml, step by step

Define the credentials in a .env file that isn’t versioned:

MONGO_ROOT_USER=admin
MONGO_ROOT_PASSWORD=cambia-esto-por-una-clave-larga-y-aleatoria

Now the compose file. We use YAML anchors to avoid repeating configuration between nodes:

x-mongo: &mongo
  image: mongo:7.0
  restart: unless-stopped
  command: >
    mongod --replSet rs0 --bind_ip_all
    --keyFile /etc/mongo/keyfile
    --wiredTigerCacheSizeGB 1
  networks: [mongo-net]
  healthcheck:
    test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"]
    interval: 10s
    timeout: 5s
    retries: 5
    start_period: 20s

services:
  mongo1:
    <<: *mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_ROOT_USER}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_ROOT_PASSWORD}
    volumes:
      - mongo1-data:/data/db
      - ./mongo-keyfile:/etc/mongo/keyfile:ro

  mongo2:
    <<: *mongo
    volumes:
      - mongo2-data:/data/db
      - ./mongo-keyfile:/etc/mongo/keyfile:ro

  mongo3:
    <<: *mongo
    volumes:
      - mongo3-data:/data/db
      - ./mongo-keyfile:/etc/mongo/keyfile:ro

  mongo-init:
    image: mongo:7.0
    restart: "no"
    depends_on:
      mongo1: { condition: service_healthy }
      mongo2: { condition: service_healthy }
      mongo3: { condition: service_healthy }
    networks: [mongo-net]
    entrypoint: >
      mongosh "mongodb://${MONGO_ROOT_USER}:${MONGO_ROOT_PASSWORD}@mongo1:27017/admin"
      --eval "try { rs.status() } catch(e) { rs.initiate({_id:'rs0',members:[
      {_id:0,host:'mongo1:27017',priority:2},
      {_id:1,host:'mongo2:27017'},
      {_id:2,host:'mongo3:27017'}]}) }"

networks:
  mongo-net:
    internal: false

volumes:
  mongo1-data:
  mongo2-data:
  mongo3-data:

What each decision does

wiredTigerCacheSizeGB caps the internal cache. By default MongoDB tries to use half the host’s RAM, and in a container with limits that ends in OOM kills. Tune it to your actual memory.

The healthcheck keeps the initialization service from starting before the nodes respond. Without it, rs.initiate fails intermittently.

Named volumes guarantee persistence. The data lives in /data/db, and as long as you don’t run down -v, it survives container recreations. The Docker documentation explains the differences between volumes and bind mounts. For databases, volumes are the most predictable option.

Priority 2 on mongo1 makes it the preferred primary after an election, handy if that host has the better disk.

Bring everything up with:

docker compose up -d
docker compose exec mongo1 mongosh -u admin -p --authenticationDatabase admin --eval "rs.status().members.map(m => [m.name, m.stateStr])"

You should see one PRIMARY and two SECONDARY.

Authentication and least privilege

The root user is only for administration. Your applications should use users with permissions scoped to their own database:

use miapp
db.createUser({
  user: "miapp_rw",
  pwd: passwordPrompt(),
  roles: [{ role: "readWrite", db: "miapp" }]
})

Also create a dedicated backup user with the built-in backup role, which can only read what’s needed to dump data.

Connection string for the application:

mongodb://miapp_rw:***@mongo1:27017,mongo2:27017,mongo3:27017/miapp?replicaSet=rs0&authSource=miapp

With this URI the driver discovers the topology and follows the new primary after a failover, with no code changes.

Secrets: out of the repository

A .env on the server is acceptable to start with, but it doesn’t scale. Rotating passwords, auditing access and keeping credentials off disk is a different league. If you want to make that leap, see how to manage secrets with OpenBao and forget about .env files in Git.

Hardening checklist

  • Don’t publish port 27017 on the host. If you need external access, use a VPN or a tunnel.
  • If the host has a public IP, filter with a firewall and block brute-force attempts. Advanced Fail2ban configuration helps here.
  • Enable TLS between nodes and clients if traffic crosses networks you don’t control.
  • Pin image versions and upgrade on a planned basis, one node at a time, starting with the secondaries.

Automated backups you can actually restore

A replica set is not a backup. If someone runs db.dropDatabase(), all three nodes obey instantly. You need independent copies, with retention, that you’ve verified.

Backup script with mongodump

mongodump with --oplog produces a point-in-time consistent copy, even with writes in progress. This matters: --oplog only works when dumping the entire instance, without --db.

#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR=/backups
RETENTION_DAYS=14
STAMP=$(date +%Y%m%d-%H%M%S)
FILE="$BACKUP_DIR/mongo-$STAMP.archive.gz"

mongodump \
  --uri="mongodb://${BACKUP_USER}:${BACKUP_PASSWORD}@mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0&authSource=admin&readPreference=secondary" \
  --oplog --gzip --archive="$FILE"

# Verificación básica: el fichero existe y no está vacío
[ -s "$FILE" ] || { echo "Backup vacío" >&2; exit 1; }

find "$BACKUP_DIR" -name 'mongo-*.archive.gz' -mtime +"$RETENTION_DAYS" -delete
echo "OK: $FILE"

Details that make the difference:

  • readPreference=secondary takes the load off the primary during the dump.
  • set -euo pipefail makes any failure abort the script instead of silently leaving a corrupt backup.
  • Rotation with find -mtime prevents filling the disk, the classic enemy of forgotten backups.

If you want to go deeper into this style of scripting, you’ll find examples in Defensive Bash scripting for backups and disk cleanup.

Scheduling it

The simplest approach is a cron job on the host that launches a one-off container:

0 3 * * * docker run --rm --network mongo_mongo-net \
  --env-file /opt/mongo/.env.backup \
  -v /opt/mongo/backups:/backups \
  -v /opt/mongo/backup.sh:/backup.sh:ro \
  mongo:7.0 bash /backup.sh >> /var/log/mongo-backup.log 2>&1

The network name depends on the project directory, so check it with docker network ls.

The 3-2-1 rule and restoration

A copy on the same disk as the data isn’t a copy. Sync the backup directory to external storage (S3-compatible, another server) with rclone or rsync. Keep at least three copies, on two media, one off-site.

And most importantly: test the restore in a separate environment, on a regular basis.

mongorestore --uri="mongodb://admin:***@mongo-test:27017/?authSource=admin" \
  --gzip --archive=mongo-20250101-030000.archive.gz --oplogReplay

A backup you’ve never restored is a hypothesis, not a guarantee.

Monitoring: don’t wait for it to fail

A secondary with replication lag or a disk at 90% won’t warn you on its own. Export metrics with mongodb_exporter and watch three signals: member status, replication lag and free volume space. Then wire the alerts to your on-call channel with this guide on Prometheus and Grafana with Slack and Telegram alerts. Add an alert for when the most recent backup file is more than 26 hours old.

Common mistakes

  1. Permission denied on the keyfile. Check for owner 999 and permissions 400.
  2. The driver can’t connect from outside Docker. The replica set advertises the names mongo1, mongo2… and the external client can’t resolve them. Connect from the same network or configure consistent DNS names.
  3. Data lost after recreating the stack. Someone used down -v. Protect the workflow with backups and avoid that flag in production.
  4. OOM kills. Cap the WiredTiger cache and set memory limits on the service.

Conclusion

A reliable MongoDB in containers doesn’t depend on a trick, but on four pillars: a replica set to tolerate failures, keyfile authentication and least-privilege users, persistent volumes and backups with a tested restore. With the compose file in this guide you have the foundation. Now add monitoring, get the copies off the server and rehearse recovery before you need it.

Keep reading