Archive · DevOps

MongoDB: Replica Sets and Backups

Three nodes for high availability, and mongodump for logical backups.

1 min read

  • MongoDB 7.0
  • Replica set
  • mongodump

A replica set has one primary and secondaries that copy its changes. If the primary fails, the others elect a new one. Use three members (or two plus an arbiter, which is not recommended).

On each node, add to /etc/mongod.conf:

replication:
  replSetName: rs0
security:
  keyFile: /etc/mongodb/keyfile     # same file, mode 400, owned by mongodb

Create the key with openssl rand -base64 756 > keyfile. Then, on one node:

rs.initiate({ _id: "rs0", members: [
  { _id: 0, host: "mongo1:27017" },
  { _id: 1, host: "mongo2:27017" },
  { _id: 2, host: "mongo3:27017" } ] })
rs.status()

Applications connect with the whole list: mongodb://mongo1,mongo2,mongo3/shop?replicaSet=rs0.

Backups:

mongodump --uri "mongodb://admin@mongo1/?replicaSet=rs0" --oplog --gzip --out /backup/$(date +%F)
mongorestore --oplogReplay --gzip /backup/2024-08-19

--oplog gives a consistent point-in-time dump. For large data sets use filesystem or EBS snapshots. Test restores regularly.