Configure MongoDB 8.0 replica set with automatic failover for high availability

Intermediate 45 min Apr 16, 2026 173 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up a MongoDB 8.0 replica set with multiple nodes and automatic failover to ensure high availability and data redundancy. This configuration provides seamless database operations even when primary nodes fail.

Prerequisites

  • 3 or more Linux servers
  • Static IP addresses configured
  • Root or sudo access on all nodes
  • Network connectivity between nodes
  • At least 4GB RAM per server

What this solves

MongoDB replica sets provide high availability through automatic failover and data redundancy across multiple database nodes. When your primary MongoDB instance fails, the replica set automatically elects a new primary from available secondary nodes, ensuring continuous database operations without manual intervention.

Step-by-step configuration

Install MongoDB 8.0 on all nodes

Install MongoDB 8.0 on each server that will be part of your replica set. You'll need at least three nodes for proper replica set functionality.

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg
echo "deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg] https://repo.mongodb.org/apt/ubuntu jammy/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
cat > /etc/yum.repos.d/mongodb-org-8.0.repo << '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://www.mongodb.org/static/pgp/server-8.0.asc
EOF
sudo dnf install -y mongodb-org

Configure MongoDB for replica set on each node

Edit the MongoDB configuration file to enable replica set functionality and bind to all network interfaces for inter-node communication.

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 0.0.0.0

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

replication:
  replSetName: "rs0"

security:
  authorization: enabled
  keyFile: /opt/mongodb/mongodb-keyfile

Create authentication keyfile

Generate a shared keyfile for secure communication between replica set members. This same keyfile must be deployed to all nodes in the replica set.

sudo mkdir -p /opt/mongodb
sudo openssl rand -base64 756 > /tmp/mongodb-keyfile
sudo mv /tmp/mongodb-keyfile /opt/mongodb/mongodb-keyfile
sudo chmod 600 /opt/mongodb/mongodb-keyfile
sudo chown mongodb:mongodb /opt/mongodb/mongodb-keyfile
Note: Copy this keyfile to the same location on all replica set members with identical permissions.

Copy keyfile to other nodes

Distribute the keyfile to all other nodes in your replica set using secure copy. Replace the IP addresses with your actual server IPs.

scp /opt/mongodb/mongodb-keyfile user@203.0.113.11:/tmp/mongodb-keyfile
scp /opt/mongodb/mongodb-keyfile user@203.0.113.12:/tmp/mongodb-keyfile

On each secondary node, move the keyfile to the correct location:

sudo mkdir -p /opt/mongodb
sudo mv /tmp/mongodb-keyfile /opt/mongodb/mongodb-keyfile
sudo chmod 600 /opt/mongodb/mongodb-keyfile
sudo chown mongodb:mongodb /opt/mongodb/mongodb-keyfile

Start MongoDB on all nodes

Enable and start the MongoDB service on each node in your replica set.

sudo systemctl enable mongod
sudo systemctl start mongod
sudo systemctl status mongod

Configure firewall rules

Open MongoDB port 27017 for communication between replica set members.

sudo ufw allow from 203.0.113.10 to any port 27017
sudo ufw allow from 203.0.113.11 to any port 27017
sudo ufw allow from 203.0.113.12 to any port 27017
sudo ufw reload
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.10" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.11" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.12" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --reload

Initialize the replica set

Connect to the primary node and initialize the replica set configuration. This step should only be performed on one node.

mongosh --host 203.0.113.10 --port 27017

Inside the MongoDB shell, initialize the replica set:

rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "203.0.113.10:27017", priority: 2 },
    { _id: 1, host: "203.0.113.11:27017", priority: 1 },
    { _id: 2, host: "203.0.113.12:27017", priority: 1 }
  ]
})

Create admin user

Create an administrative user with root privileges for replica set management. This must be done while connected to the primary node.

use admin
db.createUser({
  user: "admin",
  pwd: "SecureAdminPassword123!",
  roles: [ "root" ]
})

Configure election priorities

Set different priority values to control which node becomes primary during elections. Higher priority nodes are preferred as primary.

cfg = rs.conf()
cfg.members[0].priority = 2
cfg.members[1].priority = 1
cfg.members[2].priority = 1
rs.reconfig(cfg)

Test automatic failover

Simulate primary node failure to verify automatic failover functionality by stepping down the current primary.

rs.stepDown(60)

Monitor the election process and verify a new primary is selected:

rs.status()

Monitor replica set health

Check replica set status

Monitor the health and status of your replica set members regularly.

mongosh --host 203.0.113.10 --port 27017 -u admin -p
rs.status()
rs.conf()
rs.printSlaveReplicationInfo()

Monitor replication lag

Check replication lag between primary and secondary nodes to ensure data synchronization is healthy.

db.printSlaveReplicationInfo()
rs.printSlaveReplicationInfo()

Verify your setup

mongosh --host 203.0.113.10 --port 27017 -u admin -p

In MongoDB shell:

rs.status() db.adminCommand("isMaster") rs.conf()

Your replica set is working correctly when:

  • One node shows as PRIMARY and others as SECONDARY
  • All members show state: 1 (PRIMARY) or 2 (SECONDARY)
  • Replication lag is minimal (under 10 seconds)
  • Automatic failover completes within 30 seconds

Configure read preferences

Set up read distribution

Configure read preferences to distribute read operations across replica set members for better performance.

db.collection.find().readPref("secondary")
db.collection.find().readPref("secondaryPreferred")
db.collection.find().readPref("primaryPreferred")

Common issues

SymptomCauseFix
Node won't join replica setKeyfile permission or firewallCheck chmod 600 on keyfile, verify port 27017 access
Split brain or multiple primariesNetwork partitionEnsure odd number of members, check network connectivity
Slow failover timesDefault election timeoutTune electionTimeoutMillis in replica set config
Replication lag increasingWrite load or network issuesMonitor oplog size, check network latency between nodes
Authentication failuresKeyfile mismatchEnsure identical keyfile on all nodes with correct ownership

Performance optimization

Tune oplog size

Adjust the oplog size to handle your application's write load and ensure secondaries can catch up after maintenance.

db.adminCommand({"replSetResizeOplog": 1, "size": 16384})

Configure write concerns

Set appropriate write concerns to balance performance and durability based on your application requirements.

db.collection.insertOne(
  { name: "example" },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
)

Next steps

Automated install script

Run this to automate the entire setup

Need help?

Don't want to manage this yourself?

We handle high availability infrastructure for businesses that depend on uptime. From initial setup to ongoing operations.