MongoDB provides built-in replication through a feature called Replica Set. It allows multiple MongoDB servers to maintain copies of the same dataset, providing redundancy, high availability, and automatic failover.
Unlike traditional master-slave replication in relational databases, MongoDB Replica Sets use an election mechanism to determine which server becomes the Primary.
In this tutorial, we will configure a three-node MongoDB Replica Set using MongoDB 9.0 Community Edition on Debian 13 (Trixie).
The configuration includes:
- One Primary node for read and write operations.
- Two Secondary nodes for data replication and redundancy.
- Keyfile authentication for secure communication between MongoDB members.
- Automatic Primary election and failover.
- Replication testing and application connection configuration.
This tutorial assumes MongoDB 9.0 has already been installed on all three Debian 13 servers.
1. Understanding MongoDB Replica Set Architecture
A MongoDB Replica Set consists of multiple MongoDB instances that maintain the same dataset.
The architecture used in this tutorial:
| Server | Hostname | Private IP | Role |
|---|---|---|---|
| MongoDB 1 | mongo1.example.com | 10.10.10.11 | Primary |
| MongoDB 2 | mongo2.example.com | 10.10.10.12 | Secondary |
| MongoDB 3 | mongo3.example.com | 10.10.10.13 | Secondary |
Replace these example IP addresses and hostnames with your actual server information.
The architecture looks like this:
Applications
|
|
MongoDB Replica Set
|
+------------------+
| PRIMARY |
| MongoDB 1 |
| 10.10.10.11 |
+------------------+
|
Oplog Replication
/ \
/ \
+----------------+ +----------------+
| SECONDARY | | SECONDARY |
| MongoDB 2 | | MongoDB 3 |
| 10.10.10.12 | | 10.10.10.13 |
+----------------+ +----------------+
The Primary receives write operations and records changes in its operation log (oplog). Secondary members continuously replicate these operations and apply them to their own datasets.
MongoDB automatically conducts an election if the current Primary becomes unavailable.
A three-member configuration provides a voting majority of two. This allows the remaining two members to elect a new Primary if one server fails.
For production deployments, MongoDB recommends three data-bearing members rather than relying on an arbiter for the third vote.
2. Prerequisites
Before configuring replication, make sure all three servers meet the following requirements:
- Debian 13 (Trixie).
- MongoDB 9.0 Community Edition installed.
- All servers running the same MongoDB major version.
- Private network connectivity between all servers.
- SSH access with administrative privileges.
- TCP port 27017 allowed between replica set members.
- Synchronized system clocks.
Check MongoDB on each server:
mongod --version
mongosh --version
Check the MongoDB service:
sudo systemctl status mongod
Make sure MongoDB is installed and running before proceeding.
Important: Use separate physical or virtual machines for each replica set member. Running all three instances on one server does not provide meaningful server-level high availability.
3. Configure Hostnames
MongoDB recommends using DNS hostnames instead of IP addresses when defining replica set members.
This makes future network changes easier and avoids problems associated with IP-only member configurations.
For this tutorial, we will use the following hostnames:
mongo1.example.com
mongo2.example.com
mongo3.example.comCode language: CSS (css)
If you do not have internal DNS configured, you can use /etc/hosts on all three servers.
Edit the file:
sudo nano /etc/hosts
Add:
10.10.10.11 mongo1.example.com mongo1
10.10.10.12 mongo2.example.com mongo2
10.10.10.13 mongo3.example.com mongo3Code language: CSS (css)
Apply the same entries on all three servers.
Test hostname resolution:
getent hosts mongo1.example.com
getent hosts mongo2.example.com
getent hosts mongo3.example.comCode language: CSS (css)
Test network connectivity:
ping -c 3 mongo1.example.com
ping -c 3 mongo2.example.com
ping -c 3 mongo3.example.comCode language: CSS (css)
Also test the MongoDB port after configuring the network firewall:
nc -zv mongo1.example.com 27017
nc -zv mongo2.example.com 27017
nc -zv mongo3.example.com 27017Code language: CSS (css)
Each server must be able to communicate with the other two over TCP port 27017.
4. Configure Firewall Rules
MongoDB uses TCP port 27017 by default.
For security reasons, do not expose this port to the public internet.
Allow connections only between the three MongoDB servers using their private IP addresses.
For example, if you use UFW, the following commands can be applied to each server:
sudo ufw allow from 10.10.10.11 to any port 27017 proto tcp
sudo ufw allow from 10.10.10.12 to any port 27017 proto tcp
sudo ufw allow from 10.10.10.13 to any port 27017 proto tcpCode language: CSS (css)
If application servers need direct access to MongoDB, add their private IP addresses separately.
The firewall rules should allow the replica set members to communicate without permitting arbitrary external connections.
5. Generate MongoDB Keyfile Authentication
MongoDB Replica Set members need to authenticate with each other.
MongoDB supports internal authentication using either keyfiles or X.509 certificates.
For this tutorial, we will use keyfile authentication because it is straightforward to configure for a small or medium-sized deployment.
A keyfile acts as a shared secret between MongoDB members. All three servers must use the same keyfile contents.
Generate the Keyfile on MongoDB 1
Run the following command on the first server:
sudo openssl rand -base64 756 | sudo tee /root/mongodb-keyfile > /dev/nullCode language: JavaScript (javascript)
Set restrictive permissions:
sudo chmod 400 /root/mongodb-keyfile
Verify the file:
sudo ls -l /root/mongodb-keyfile
Copy the Keyfile to MongoDB 2 and MongoDB 3
Transfer the file securely using SCP:
sudo scp /root/mongodb-keyfile root@10.10.10.12:/root/
sudo scp /root/mongodb-keyfile root@10.10.10.13:/root/Code language: JavaScript (javascript)
On all three servers, install the keyfile in the MongoDB configuration directory:
sudo install \
-o mongodb \
-g mongodb \
-m 400 \
/root/mongodb-keyfile \
/etc/mongodb-keyfile
Verify ownership and permissions:
sudo ls -l /etc/mongodb-keyfile
Expected:
-r-------- 1 mongodb mongodb ... /etc/mongodb-keyfile
The keyfile must be readable by the MongoDB process but inaccessible to other users.
Important: Never generate a different keyfile for each server. All replica set members must share at least one common key.
6. Configure MongoDB Replica Set
Now configure each MongoDB instance to participate in the same replica set.
We will use the replica set name:
rs0
Edit the MongoDB configuration file on each server:
sudo nano /etc/mongod.conf
MongoDB 1 Configuration
On the first server, configure:
storage:
dbPath: /var/lib/mongodb
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1,10.10.10.11
security:
keyFile: /etc/mongodb-keyfile
replication:
replSetName: rs0Code language: JavaScript (javascript)
MongoDB 2 Configuration
On the second server:
storage:
dbPath: /var/lib/mongodb
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1,10.10.10.12
security:
keyFile: /etc/mongodb-keyfile
replication:
replSetName: rs0Code language: JavaScript (javascript)
MongoDB 3 Configuration
On the third server:
storage:
dbPath: /var/lib/mongodb
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1,10.10.10.13
security:
keyFile: /etc/mongodb-keyfile
replication:
replSetName: rs0Code language: JavaScript (javascript)
These examples show the relevant configuration sections. Preserve any other existing configuration settings, such as storage engine, journaling, or system logging options, rather than accidentally removing them.
The important configuration parameters are:
net.bindIp: Allows MongoDB to listen on localhost and its private network interface.security.keyFile: Enables internal authentication between members and client authorization.replication.replSetName: Identifies the replica set.
Important: If you previously created a MongoDB administrator account in the standalone installation tutorial, keep its credentials. You will need them when authenticating to the first node.
7. Restart MongoDB on All Servers
After updating the configuration files, restart MongoDB on all three servers.
Execute:
sudo systemctl restart mongod
Check the service:
sudo systemctl status mongod
Verify that MongoDB is listening on the private network interface:
sudo ss -lntp | grep 27017
If MongoDB fails to start, inspect the logs:
sudo journalctl -u mongod -n 100 --no-pager
Or:
sudo tail -100 /var/log/mongodb/mongod.logCode language: JavaScript (javascript)
Do not continue until all three MongoDB instances are running successfully.
8. Initialize the Replica Set
Now we can initialize the replica set.
Connect to MongoDB 1:
mongosh -u mongoAdmin -p --authenticationDatabase admin
Enter the administrator password.
If you have not created any users yet, MongoDB’s localhost exception can be used for initial setup by connecting locally without authentication. This exception is available only while no users or roles have been created.
Execute the following command:
rs.initiate({
_id: "rs0",
members: [
{
_id: 0,
host: "mongo1.example.com:27017"
},
{
_id: 1,
host: "mongo2.example.com:27017"
},
{
_id: 2,
host: "mongo3.example.com:27017"
}
]
})Code language: CSS (css)
You should receive a response similar to:
{
ok: 1
}Code language: CSS (css)
MongoDB will begin the election process and select one member as the Primary.
Important: Execute rs.initiate() only once, from one member of the replica set. Do not run it separately on all three servers.
9. Verify Replica Set Status
After initialization, check the replica set status:
rs.status()Code language: CSS (css)
You should see three members with the following states:
| Member | Expected state |
|---|---|
| mongo1.example.com | PRIMARY |
| mongo2.example.com | SECONDARY |
| mongo3.example.com | SECONDARY |
The actual Primary can be any of the three members, depending on the election.
You can also run:
rs.isMaster()Code language: CSS (css)
For newer MongoDB deployments, db.hello() is the preferred command for inspecting the current member’s role:
db.hello()Code language: CSS (css)
Look for:
{
setName: "rs0",
isWritablePrimary: true
}Code language: CSS (css)
On a Secondary, secondary should be true.
To get a concise overview of all members:
rs.status().members.map(member => ({
name: member.name,
state: member.stateStr,
health: member.health
}))Code language: JavaScript (javascript)
Expected output:
[
{
name: "mongo1.example.com:27017",
state: "PRIMARY",
health: 1
},
{
name: "mongo2.example.com:27017",
state: "SECONDARY",
health: 1
},
{
name: "mongo3.example.com:27017",
state: "SECONDARY",
health: 1
}
]Code language: JavaScript (javascript)
The order and Primary assignment may differ.
10. Test Data Replication
Let’s verify that data written to the Primary is replicated to the Secondary members.
Connect to the current Primary and select a test database:
use replication_testCode language: PHP (php)
Insert a document:
db.servers.insertOne({
hostname: "mongo1",
message: "MongoDB Replica Set Test",
createdAt: new Date()
})Code language: CSS (css)
Check the inserted document:
db.servers.find().pretty()Code language: CSS (css)
Now connect to one of the Secondary servers.
You can connect directly using:
mongosh "mongodb://mongo2.example.com:27017/?directConnection=true" \
-u mongoAdmin \
-p \
--authenticationDatabase adminCode language: JavaScript (javascript)
Set the read preference to Secondary:
db.getMongo().setReadPref("secondary")Code language: CSS (css)
Select the test database:
use replication_testCode language: PHP (php)
Read the replicated document:
db.servers.find().pretty()Code language: CSS (css)
You should see the document inserted on the Primary.
By default, MongoDB directs application reads to the Primary. Explicitly selecting the Secondary read preference is necessary to read from a Secondary.
11. Test Automatic Failover
One of the biggest advantages of MongoDB Replica Sets is automatic failover.
If the Primary server becomes unavailable, the remaining voting members can elect another Secondary as the new Primary.
For this test, first identify which server is currently Primary:
db.hello()Code language: CSS (css)
Suppose MongoDB 1 is currently the Primary.
On MongoDB 1, stop the MongoDB service:
sudo systemctl stop mongod
Wait for the election to complete.
Connect to MongoDB 2 or MongoDB 3:
mongosh -u mongoAdmin -p --authenticationDatabase admin
Check the current replica set status:
rs.status()Code language: CSS (css)
Check the current member’s role:
db.hello()Code language: CSS (css)
One of the remaining members should now report:
isWritablePrimary: trueCode language: JavaScript (javascript)
This demonstrates that MongoDB can automatically promote a Secondary when the existing Primary becomes unavailable.
Restart the original Primary:
sudo systemctl start mongod
It should rejoin the replica set and become a Secondary after recovering and synchronizing its data.
Important: Automatic failover is not instantaneous. Applications may temporarily experience connection errors during an election. Production applications must use a replica-set-aware MongoDB driver and retry appropriate operations.
12. Configure MongoDB Application Connection String
Applications should connect using the replica set connection string rather than connecting to only one MongoDB server.
For example:
mongodb://mongoAdmin:[email protected]:27017,mongo2.example.com:27017,mongo3.example.com:27017/?replicaSet=rs0&authSource=adminCode language: JavaScript (javascript)
Replace PASSWORD with the actual password.
For application deployments, create a dedicated database user instead of using the root administrative account.
Example:
use application_db
db.createUser({
user: "appUser",
pwd: passwordPrompt(),
roles: [
{
role: "readWrite",
db: "application_db"
}
]
})Code language: CSS (css)
The application connection string becomes:
mongodb://appUser:[email protected]:27017,mongo2.example.com:27017,mongo3.example.com:27017/?replicaSet=rs0&authSource=application_dbCode language: JavaScript (javascript)
With this configuration, the MongoDB driver can discover the current Primary and automatically adjust when a new election occurs.
For production applications, use environment variables or a secrets manager to store database credentials instead of hardcoding them in application source code.
13. Monitor Replica Set Health
MongoDB provides several built-in commands for monitoring replication.
Check Replica Set Status
rs.status()Code language: CSS (css)
Check Replica Set Configuration
rs.conf()Code language: CSS (css)
Check Replication Information
rs.printReplicationInfo()Code language: CSS (css)
Check Secondary Replication Lag
rs.printSecondaryReplicationInfo()Code language: CSS (css)
Check Current Member Role
db.hello()Code language: CSS (css)
These commands are useful when troubleshooting replication problems, monitoring synchronization, and verifying failover behavior.
For production deployments, consider integrating MongoDB metrics into your monitoring platform.
14. Important Production Recommendations
Before deploying MongoDB Replica Sets in production, consider the following recommendations.
Network security
- Use private network interfaces for replica set communication.
- Restrict TCP port 27017 to trusted application servers and MongoDB members.
- Enable keyfile or X.509 internal authentication.
- Consider TLS encryption for network communication.
High availability
- Deploy each member on a separate server.
- Distribute members across availability zones when possible.
- Keep all replica set members on compatible MongoDB versions.
- Monitor replica set elections and member availability.
Data protection
- Configure regular MongoDB backups.
- Test database restoration procedures.
- Monitor disk utilization and storage performance.
- Understand that replication is not a replacement for backups.
Application connectivity
- Use a replica-set-aware MongoDB connection string.
- Use dedicated application database accounts.
- Configure appropriate read and write concerns.
- Implement retry logic for transient connection failures.
Conclusion
MongoDB Replica Sets provide a built-in mechanism for database replication and high availability.
By configuring three MongoDB servers on Debian 13, we have established a Primary-Secondary architecture with internal authentication, automatic elections, and data replication.
The configuration also allows applications to connect through a single replica set connection string, reducing dependency on an individual database server.
For production environments, combining MongoDB Replica Sets with proper monitoring, regular backups, network security, and tested recovery procedures provides a stronger database infrastructure.