
Understanding MongoDB Replica Sets for Production VPS Hosting
A MongoDB replica set provides automatic failover and data redundancy across multiple VPS instances. Unlike standalone MongoDB installations, replica sets maintain synchronized copies of your data across multiple nodes. This ensures zero data loss during hardware failures or maintenance windows.
The architecture is straightforward. A primary node handles all write operations while secondary nodes replicate data from the primary.
When the primary fails, the remaining nodes automatically elect a new primary within seconds.
This tutorial walks through setting up a three-node replica set on Ubuntu 24.04 VPS instances. You'll configure authentication, enable SSL connections, and implement monitoring for production-ready reliability.
Prerequisites and VPS Requirements
You need three Ubuntu 24.04 VPS instances with at least 2GB RAM and 20GB storage each. Enable private networking for secure inter-node communication.
Open these ports in your firewall:
- 27017 (MongoDB default port)
- 22 (SSH access)
Each VPS needs a static IP address and proper hostname resolution. Configure your /etc/hosts file on all nodes:
192.168.1.10 mongo-primary
192.168.1.11 mongo-secondary1
192.168.1.12 mongo-secondary2
The HostMyCode VPS platform provides private networking and flexible firewall configuration. This makes it ideal for multi-node database deployments.
Installing MongoDB 7.0 on All VPS Nodes
Install MongoDB 7.0 on each VPS node using the official repository. Run these commands on all three servers:
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update
sudo apt install -y mongodb-org
Prevent automatic updates that could break your replica set:
echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-database hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-mongosh hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections
Create the MongoDB data directory and set proper permissions:
sudo mkdir -p /var/lib/mongodb
sudo chown mongodb:mongodb /var/lib/mongodb
sudo chmod 755 /var/lib/mongodb
Configuring MongoDB Replica Set Operation
Edit the MongoDB configuration file on each node. The primary difference between nodes will be the hostname binding.
On the primary node (mongo-primary), edit /etc/mongod.conf:
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
logRotate: rename
net:
port: 27017
bindIp: 127.0.0.1,192.168.1.10
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: enabled
keyFile: /etc/mongodb-keyfile
replication:
replSetName: "rs0"
On secondary nodes, only change the bindIp address to match each server's private IP.
Use 192.168.1.11 for mongo-secondary1 and 192.168.1.12 for mongo-secondary2.
Setting Up Authentication and Security
Generate a keyfile for inter-node authentication. Run this on the primary node:
sudo openssl rand -base64 756 > /tmp/mongodb-keyfile
sudo mv /tmp/mongodb-keyfile /etc/mongodb-keyfile
sudo chmod 400 /etc/mongodb-keyfile
sudo chown mongodb:mongodb /etc/mongodb-keyfile
Copy the keyfile to all secondary nodes using scp:
scp /etc/mongodb-keyfile user@mongo-secondary1:/tmp/
scp /etc/mongodb-keyfile user@mongo-secondary2:/tmp/
On each secondary node, move the keyfile to the correct location:
sudo mv /tmp/mongodb-keyfile /etc/mongodb-keyfile
sudo chmod 400 /etc/mongodb-keyfile
sudo chown mongodb:mongodb /etc/mongodb-keyfile
For SSL configuration, reference our SSL certificate management guide. This shows how to secure MongoDB connections with Let's Encrypt certificates.
Initializing the MongoDB Replica Set
Start MongoDB on all nodes without authentication first:
sudo systemctl start mongod
sudo systemctl enable mongod
Connect to the primary node and initialize the replica set. Comment out the keyFile line in /etc/mongod.conf temporarily:
mongosh --host mongo-primary:27017
Run the replica set initialization command:
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongo-primary:27017", priority: 2 },
{ _id: 1, host: "mongo-secondary1:27017", priority: 1 },
{ _id: 2, host: "mongo-secondary2:27017", priority: 1 }
]
})
Wait for the replica set to initialize. Check the status:
rs.status()
Create an administrative user while still connected to the primary:
use admin
db.createUser({
user: "admin",
pwd: "your-strong-password",
roles: [ { role: "root", db: "admin" } ]
})
Enabling Authentication and Testing Failover
Uncomment the keyFile line in /etc/mongod.conf on all nodes and restart MongoDB:
sudo systemctl restart mongod
Test authentication by connecting with credentials:
mongosh --host mongo-primary:27017 -u admin -p
Verify all nodes are communicating properly:
rs.status()
Test automatic failover by stopping MongoDB on the primary:
sudo systemctl stop mongod
Connect to a secondary node and verify it becomes primary within 12 seconds:
mongosh --host mongo-secondary1:27017 -u admin -p
rs.status()
Start the original primary back up. It will rejoin as a secondary automatically.
Managing replica sets requires reliable VPS infrastructure with consistent networking and performance. HostMyCode database hosting provides optimized VPS instances with SSD storage and private networking, perfect for production MongoDB deployments.
Monitoring and Maintenance Best Practices
Set up MongoDB logs rotation to prevent disk space issues:
sudo logrotate -f /etc/logrotate.d/mongodb-server
Monitor replica set health with these commands:
# Check replica set configuration
rs.conf()
# Monitor replication lag
rs.printSlaveReplicationInfo()
# Check oplog size
db.oplog.rs.stats()
Enable MongoDB's built-in monitoring:
db.enableFreeMonitoring()
For production environments, integrate with external monitoring solutions. Our VPS monitoring guide covers Prometheus and Grafana setup for database metrics.
Common Issues and Troubleshooting
If nodes can't communicate, check firewall rules and network connectivity:
# Test connectivity between nodes
telnet mongo-secondary1 27017
When authentication fails, verify keyfile permissions and contents are identical on all nodes:
sudo ls -la /etc/mongodb-keyfile
sudo md5sum /etc/mongodb-keyfile
For split-brain scenarios, check network partitions. Ensure you have an odd number of voting members.
Monitor disk space regularly. MongoDB requires significant space for oplog and journaling:
df -h /var/lib/mongodb
Frequently Asked Questions
Can I add more nodes to my replica set later?
Yes, you can add additional secondary nodes using rs.add("hostname:27017"). The maximum recommended replica set size is 50 members, with up to 7 voting members.
How much replication lag is acceptable in production?
Replication lag under 1 second is ideal for most applications. Monitor this with rs.printSlaveReplicationInfo() and investigate if lag exceeds 10 seconds consistently.
What happens if all secondary nodes fail?
The primary can continue accepting writes but cannot acknowledge them with write concern "majority". The primary will step down if it loses contact with a majority of replica set members.
Should I run replica set nodes on the same VPS provider?
For high availability, distribute nodes across different availability zones or data centers. HostMyCode offers VPS locations in multiple regions for geographic redundancy.
How do I backup a replica set?
Use mongodump against a secondary node to avoid impacting primary performance. You can also use filesystem snapshots if your VPS provider supports consistent point-in-time snapshots.