How to Set Up Mongodb Replica Set with Keyfile Authentication and Automatic Primary Failover on Ubuntu Server
Learning how to set up MongoDB Replica Set with Keyfile Authentication and Automatic Primary Failover on Ubuntu Server is one of the most valuable skills for any database administrator. A replica set gives you high availability, data redundancy, and automatic failover when a primary node goes down. In this tutorial, you will configure a three-node MongoDB replica set secured with keyfile authentication. You will also verify that automatic primary election works correctly. By the end, your MongoDB cluster will be production-ready. This guide targets Ubuntu 22.04 LTS, but the steps work on Ubuntu 20.04 as well.
Prerequisites and Requirements for Your MongoDB Replica Set
Before you start, make sure you have the following in place.
Hardware and software requirements:
- Three Ubuntu servers (physical or virtual) , label them
mongo1,mongo2, andmongo3 - Each server needs at least 2 GB RAM and 2 CPU cores
- MongoDB 6.x or 7.x installed on all three nodes
- Root or sudo access on every server
- All three servers on the same private network
- Port 27017 open between all nodes
Assumed knowledge: You should be comfortable with basic Linux commands and SSH. You don’t need prior MongoDB experience, but it helps.
Estimated time: 45–60 minutes.
Install MongoDB on all three nodes before continuing. Follow the official MongoDB installation guide for Ubuntu to get the correct packages from MongoDB’s repository.
How to Set Up MongoDB Replica Set with Keyfile Authentication Step by Step
Related tutorial: How to Containerize a Node.js Web Application with Docker
Follow these steps on each server unless a step says otherwise.
Step 1: Update /etc/hosts on all three nodes
Each server must resolve the other hostnames. Add these lines to /etc/hosts on all three machines. Replace the IPs with your actual private IP addresses.
sudo nano /etc/hosts
Add the following lines:
192.168.1.10 mongo1
192.168.1.11 mongo2
192.168.1.12 mongo3
Save and close the file.
Step 2: Generate the keyfile on mongo1
The keyfile secures communication between replica set members. Run this only on mongo1, then copy it to the other nodes.
openssl rand -base64 756 > /etc/mongodb-keyfile
chmod 400 /etc/mongodb-keyfile
sudo chown mongodb:mongodb /etc/mongodb-keyfile
Now copy the keyfile to mongo2 and mongo3:
scp /etc/mongodb-keyfile user@mongo2:/etc/mongodb-keyfile
scp /etc/mongodb-keyfile user@mongo3:/etc/mongodb-keyfile
Run the chmod and chown commands on mongo2 and mongo3 as well.
Step 3: Configure mongod.conf on all three nodes
Edit the MongoDB configuration file on each server:
sudo nano /etc/mongod.conf
Update the file with these settings. Change bindIp to match each server’s private IP:
net:
port: 27017
bindIp: 0.0.0.0
replication:
replSetName: "rs0"
security:
keyFile: /etc/mongodb-keyfile
authorization: enabled
Save the file on all three nodes.
Step 4: Restart MongoDB on all three nodes
sudo systemctl restart mongod
sudo systemctl enable mongod
Check the service is running:
sudo systemctl status mongod
You should see active (running) in green.
Step 5: Initiate the replica set from mongo1
Connect to the MongoDB shell on mongo1:
mongosh
Run the initiation command:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo1:27017" },
{ _id: 1, host: "mongo2:27017" },
{ _id: 2, host: "mongo3:27017" }
]
})
You should see { ok: 1 } as the response. The shell prompt will change to rs0 [direct: primary] within a few seconds.
Step 6: Create an admin user
Once mongo1 is the primary, create your admin account:
use admin
db.createUser({
user: "adminUser",
pwd: "StrongPassword123!",
roles: [ { role: "root", db: "admin" } ]
})
From now on, authenticate with this user when connecting:
mongosh -u adminUser -p StrongPassword123! --authenticationDatabase admin
Step 7: Verify replica set status
Check the replica set health:
rs.status()
You will see all three members listed. One shows "stateStr": "PRIMARY". The others show "stateStr": "SECONDARY".
Step 8: Test automatic primary failover
Stop MongoDB on mongo1 to simulate a failure:
sudo systemctl stop mongod
Connect to mongo2 or mongo3 and run:
rs.status()
Within 10–30 seconds, one of the remaining nodes will become the new primary. This confirms automatic failover is working.
Troubleshooting Common MongoDB Replica Set Issues
Even with careful setup, things can go wrong. Here are the most common problems and how to fix them.
Members stuck in STARTUP state
This usually means the nodes can’t reach each other. Check your firewall rules:
sudo ufw allow 27017/tcp
Also verify the /etc/hosts entries are correct on all nodes.
Keyfile permission errors
MongoDB is strict about keyfile permissions. The file must be owned by the mongodb user and set to 400. If you see permissions on /etc/mongodb-keyfile are too open, run:
sudo chmod 400 /etc/mongodb-keyfile
sudo chown mongodb:mongodb /etc/mongodb-keyfile
Authentication failures after restart
If you can’t log in after a restart, make sure you’re connecting with the correct authentication database:
mongosh --host mongo1 -u adminUser -p --authenticationDatabase admin
Replica set won’t elect a new primary
You need at least two nodes alive for an election to succeed. With only one node remaining, the replica set goes read-only. This is expected behavior. Consider adding an arbiter node if you want quorum with fewer full data nodes.
mongod.conf changes not taking effect
Always restart the service after editing the config file:
sudo systemctl restart mongod
Conclusion: Your MongoDB Replica Set Is Ready
You now know how to set up MongoDB Replica Set with Keyfile Authentication and Automatic Primary Failover on Ubuntu Server. You configured three nodes, secured them with a shared keyfile, initiated the replica set, and confirmed that automatic primary election works when a node fails. Your data is now replicated across three servers, and your application can survive a node outage without manual intervention.
From here, you can connect your application using a MongoDB connection string that includes all three hosts. You should also set up log rotation, regular backups, and monitoring with MongoDB Atlas or a self-hosted tool like Prometheus. Keeping your MongoDB version updated is also critical for security and performance.
