Log inSign up

Run a three-member MongoDB replica set securely

Install the same MongoDB release from the official repository on three servers, copy one shared keyfile to each, give every node a TLS certificate signed by your own small CA, and set replSetName, keyFile and net.tls.mode: requireTLS in /etc/mongod.conf. Open port 27017 only to the other two members and your app server, then run rs.initiate() once and create an admin user through the localhost exception.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

Why three members, and how are they connected?

Three voting members let the set elect a new primary when any one of them fails, because the remaining two still form a majority. With only two, losing either leaves no majority and the survivor drops to read only.

This guide uses three servers, ideally in different cities:

  • mongo1.example.net at 198.51.100.24
  • mongo2.example.net at 198.51.100.25
  • mongo3.example.net at 198.51.100.26

The members talk over their public addresses, as there is no private network between servers. That makes three layers mandatory: a keyfile so only members can join, TLS so traffic and credentials are encrypted, and firewall rules so port 27017 is closed to the rest of the internet. Create the A records before you start (see the DNS records tutorial), because members find each other and verify certificates by name.

Current MongoDB builds for x86 need a CPU with AVX. Run grep -m1 -o avx /proc/cpuinfo; it should print avx.

How do you install MongoDB on each server?

Add the official MongoDB 8.0 repository and install mongodb-org. Do the same on all three machines so the versions match.

Ubuntu 24.04 (use jammy on 22.04)

sudo apt install -y gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo apt update && sudo apt install -y mongodb-org

Debian 12

Import the same key as above, then add the Debian line:

echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Rocky Linux 9 and AlmaLinux 9

sudo tee /etc/yum.repos.d/mongodb-org-8.0.repo >/dev/null <<'EOF'
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
EOF
sudo dnf install -y mongodb-org
mongod --version
sudo systemctl enable mongod

Check the MongoDB release notes for which distribution versions each series supports before you pick an image. Do not start the service yet. The single server MongoDB guide covers a standalone install.

How do you create the shared keyfile?

Generate a random keyfile once and copy the identical file to every member. Members prove to each other that they belong to the set by holding the same key.

sudo mkdir -p /etc/mongodb
openssl rand -base64 756 | sudo tee /etc/mongodb/keyfile >/dev/null
sudo chmod 400 /etc/mongodb/keyfile
# Ubuntu/Debian user: mongodb   Rocky/Alma user: mongod
sudo chown mongodb:mongodb /etc/mongodb/keyfile

Copy it to the other two servers with scp through your SSH login, then fix owner and mode there too. MongoDB refuses to start if the keyfile is readable by group or others. Enabling a keyfile also switches on user authorization, so every client must log in from now on.

How do you issue TLS certificates for the members?

Create a small private CA on one machine, sign one certificate per member, and install the CA certificate everywhere. Each member certificate must name its host and allow both server and client use, because members connect to each other.

mkdir ~/mongo-ca && cd ~/mongo-ca
openssl req -x509 -newkey rsa:4096 -nodes -days 3650 -keyout ca.key -out ca.crt -subj "/CN=Mongo Internal CA"
for n in 1 2 3; do
  openssl req -newkey rsa:3072 -nodes -keyout mongo$n.key -out mongo$n.csr -subj "/CN=mongo$n.example.net"
  printf "subjectAltName=DNS:mongo$n.example.net,DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth,clientAuth\n" > mongo$n.ext
  openssl x509 -req -in mongo$n.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 825 -extfile mongo$n.ext -out mongo$n.crt
  cat mongo$n.crt mongo$n.key > mongo$n.pem
done

On each server, place its own .pem and the shared ca.crt in /etc/mongodb/tls/, owned by the MongoDB user with mode 600 for the PEM file. Keep ca.key off the database servers once you are done signing. Adding localhost to the names lets you use the localhost exception later without disabling hostname checks.

What goes in mongod.conf?

Bind to localhost plus the public address, require TLS, point at the keyfile and name the set. This is the file for the first member; change the address and certificate name on the others.

storage:
  dbPath: /var/lib/mongodb        # /var/lib/mongo on Rocky/Alma
systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true
net:
  port: 27017
  bindIp: 127.0.0.1,198.51.100.24
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/mongodb/tls/mongo1.pem
    CAFile: /etc/mongodb/tls/ca.crt
    allowConnectionsWithoutCertificates: true
security:
  keyFile: /etc/mongodb/keyfile
  authorization: enabled
replication:
  replSetName: rs0

With allowConnectionsWithoutCertificates set, applications only need to trust the CA and log in with a password, while members still present their certificates to each other. Start the service and confirm it listens:

sudo systemctl restart mongod
sudo ss -tlnp | grep 27017
sudo tail -n 30 /var/log/mongodb/mongod.log

Which firewall rules does each member need?

Allow port 27017 from the other two members and from the application server, nothing more. Here the app runs at 198.51.100.40; these are the rules for mongo1.

Ubuntu and Debian

for ip in 198.51.100.25 198.51.100.26 198.51.100.40; do
  sudo ufw allow from $ip to any port 27017 proto tcp
done
sudo ufw status

Rocky Linux and AlmaLinux

for ip in 198.51.100.25 198.51.100.26 198.51.100.40; do
  sudo firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=$ip/32 port port=27017 protocol=tcp accept"
done
sudo firewall-cmd --reload

On Rocky and Alma with SELinux enforcing, the packaged policy already allows mongod on its default port. If you move it, read the SELinux basics guide first.

How do you initiate the set and create users?

Connect to one member over localhost, run rs.initiate() with all three hosts, then create the first admin through the localhost exception.

mongosh --tls --tlsCAFile /etc/mongodb/tls/ca.crt --host localhost
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo1.example.net:27017" },
    { _id: 1, host: "mongo2.example.net:27017" },
    { _id: 2, host: "mongo3.example.net:27017" }
  ]
})
// wait a few seconds until the prompt shows PRIMARY, then:
db.getSiblingDB("admin").createUser({ user: "admin", pwd: passwordPrompt(), roles: [ { role: "root", db: "admin" } ] })

Log in again as that user and give the application its own account limited to one database:

mongosh "mongodb://mongo1.example.net/admin?replicaSet=rs0&tls=true&tlsCAFile=/etc/mongodb/tls/ca.crt" -u admin
use shop
db.createUser({ user: "shopapp", pwd: passwordPrompt(), roles: [ { role: "readWrite", db: "shop" } ] })
rs.status().members.map(m => m.name + " " + m.stateStr)

You should see one PRIMARY and two SECONDARY members. Applications connect with all three hosts in the string, replicaSet=rs0, tls=true and authSource=shop, so the driver follows the primary after an election.

How do you test failover and maintain the set?

Stop the primary and watch another member take over within seconds; then start it again and it rejoins as a secondary.

sudo systemctl stop mongod      # on the current primary
mongosh "mongodb://mongo2.example.net/admin?replicaSet=rs0&tls=true&tlsCAFile=/etc/mongodb/tls/ca.crt" -u admin --eval "rs.status().members.map(m => m.name + ' ' + m.stateStr)"
sudo systemctl start mongod

For upgrades, patch one secondary at a time, then call rs.stepDown() on the primary and patch it last. Keep separate backups with mongodump or filesystem copies taken from a secondary, because a mistaken delete replicates to every member. Track certificate expiry dates and renew them before they lapse, since an expired member certificate drops that node out of the set.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A2-4each member of a small set2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months
A4-8working sets that need more cache4 vCPU, 8 GB RAM, 180 GB NVMe$28.80/mo$86.40 for 3 months

Questions about MongoDB replica set

Can I use two data servers and a small arbiter?

You can, but an arbiter holds no data, so with one data member down you have no redundancy and majority write concerns stall. Three data-bearing members is the safer layout.

Is the keyfile enough without TLS?

No. The keyfile authenticates members but does not encrypt anything. Across public IPs you need TLS too, otherwise documents and login exchanges travel in the clear.

Do clients need their own certificates?

Not with allowConnectionsWithoutCertificates: true. They verify the server against your CA and log in with a username and password. Remove that line if you want to require client certificates.

Why does mongod fail to start after adding the keyfile?

Usually the file permissions. It must be owned by the MongoDB user and readable only by that user (mode 400 or 600). The log in /var/log/mongodb/mongod.log names the exact problem.

Can members be in different cities?

Yes. Spreading them out protects against a single location failing. Writes with a majority write concern then wait for a second member, so expect latency equal to the round trip between the closest two.