BLOG POSTS
Configuring a MongoDB Replica Set on Ubuntu 24

Configuring a MongoDB Replica Set on Ubuntu 24

MongoDB replica sets are a fundamental aspect of building resilient and scalable database architectures. Setting up a replica set involves configuring multiple MongoDB instances to work together, providing automatic failover, data redundancy, and improved read performance through read preference distribution. This guide walks you through configuring a three-node MongoDB replica set on Ubuntu 24, covering installation, configuration, initialization, and troubleshooting common issues you’ll encounter in production environments.

How MongoDB Replica Sets Work

A MongoDB replica set consists of multiple mongod instances that maintain identical data sets. The architecture includes one primary node that handles all write operations and multiple secondary nodes that replicate data from the primary. When the primary becomes unavailable, the replica set automatically elects a new primary through a consensus mechanism.

The key components include:

  • Primary node: Accepts write operations and logs changes to the oplog
  • Secondary nodes: Replicate data by tailing the primary’s oplog
  • Arbiter (optional): Participates in elections but doesn’t store data
  • Oplog: A capped collection storing ordered operations for replication

Replica sets use a heartbeat mechanism where members send ping requests every 2 seconds. If a primary doesn’t respond within 10 seconds (electionTimeoutMillis), secondaries initiate an election process.

Prerequisites and System Requirements

Before diving into the setup, ensure your Ubuntu 24 systems meet these requirements:

Component Minimum Recommended
RAM 4GB 8GB+
Storage 20GB SSD with 100GB+
Network 1Gbps 10Gbps for high-throughput
MongoDB Version 7.0+ Latest stable

You’ll need three Ubuntu 24 servers. For production deployments, consider using dedicated servers to ensure consistent performance and network isolation.

Step-by-Step MongoDB Installation

First, install MongoDB on all three servers. MongoDB isn’t available in Ubuntu’s default repositories, so we’ll use the official MongoDB repository.

# Import MongoDB GPG key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg

# Add MongoDB repository
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

# Update package list and install MongoDB
sudo apt update
sudo apt install -y mongodb-org

# Prevent automatic updates
sudo apt-mark hold mongodb-org mongodb-org-database mongodb-org-server mongodb-org-mongos mongodb-org-tools

Start and enable MongoDB service on each server:

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

Network Configuration and Security Setup

Configure the firewall to allow MongoDB communication between replica set members. MongoDB uses port 27017 by default:

# Allow MongoDB port from other replica set members
sudo ufw allow from SERVER_1_IP to any port 27017
sudo ufw allow from SERVER_2_IP to any port 27017
sudo ufw allow from SERVER_3_IP to any port 27017

# Enable firewall if not already enabled
sudo ufw --force enable

Edit the hosts file on each server to include all replica set members:

sudo nano /etc/hosts

# Add these lines (replace with your actual IPs)
10.0.1.10   mongo-primary
10.0.1.11   mongo-secondary1
10.0.1.12   mongo-secondary2

MongoDB Configuration for Replica Set

Configure MongoDB for replica set operation by editing the configuration file on each server:

sudo nano /etc/mongod.conf

Update the configuration with these settings:

# Network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,INTERNAL_IP_ADDRESS

# Storage configuration
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2

# Process management
processManagement:
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid
  timeZoneInfo: /usr/share/zoneinfo

# Replica set configuration
replication:
  replSetName: "rs0"
  oplogSizeMB: 2048

# Security (enable after initial setup)
# security:
#   authorization: enabled
#   keyFile: /etc/mongod-keyfile

Replace INTERNAL_IP_ADDRESS with each server’s internal IP. Restart MongoDB on all servers:

sudo systemctl restart mongod

Replica Set Initialization

Connect to the intended primary server and initialize the replica set:

mongosh --host mongo-primary:27017

Initialize the replica set with this configuration:

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
    }
  ]
})

The higher priority value (2) makes mongo-primary the preferred primary node. Check the replica set status:

rs.status()

Wait for all members to reach SECONDARY or PRIMARY state. This typically takes 30-60 seconds.

Security Configuration and Authentication

For production environments, enable authentication and inter-node communication security. Create a keyfile for internal authentication:

# Generate keyfile on primary
openssl rand -base64 756 > /tmp/mongo-keyfile
chmod 400 /tmp/mongo-keyfile
sudo mv /tmp/mongo-keyfile /etc/mongod-keyfile
sudo chown mongodb:mongodb /etc/mongod-keyfile

Copy the keyfile to all replica set members:

scp /etc/mongod-keyfile user@mongo-secondary1:/tmp/
scp /etc/mongod-keyfile user@mongo-secondary2:/tmp/

On secondary nodes, move and set permissions:

sudo mv /tmp/mongod-keyfile /etc/mongod-keyfile
sudo chown mongodb:mongodb /etc/mongod-keyfile
sudo chmod 400 /etc/mongod-keyfile

Create an administrative user before enabling authentication:

# Connect to primary
mongosh --host mongo-primary:27017

# Create admin user
use admin
db.createUser({
  user: "admin",
  pwd: passwordPrompt(),
  roles: [
    { role: "userAdminAnyDatabase", db: "admin" },
    { role: "readWriteAnyDatabase", db: "admin" },
    { role: "dbAdminAnyDatabase", db: "admin" },
    { role: "clusterAdmin", db: "admin" }
  ]
})

Enable security in the configuration file and restart all nodes:

security:
  authorization: enabled
  keyFile: /etc/mongod-keyfile

Performance Optimization and Best Practices

Optimize your replica set configuration based on your workload requirements:

Setting Development Production High Performance
oplogSizeMB 1024 5120 10240+
cacheSizeGB 1 50% of RAM 60% of RAM
journalCommitInterval 100ms 100ms 50ms
syncPeriodSecs 60 60 30

Key performance considerations:

  • Place data, logs, and journal on separate disks when possible
  • Use XFS filesystem for better performance with WiredTiger
  • Disable transparent huge pages (THP) for consistent latency
  • Configure appropriate read preferences for your application

Disable THP on all servers:

# Create systemd service to disable THP
sudo tee /etc/systemd/system/disable-thp.service > /dev/null < /dev/null'
ExecStart=/bin/sh -c 'echo never | tee /sys/kernel/mm/transparent_hugepage/defrag > /dev/null'

[Install]
WantedBy=basic.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable disable-thp
sudo systemctl start disable-thp

Testing and Validation

Verify your replica set works correctly by testing failover scenarios and data consistency:

# Test write operations
mongosh --host "rs0/mongo-primary:27017,mongo-secondary1:27017,mongo-secondary2:27017" -u admin

# Insert test data
use testdb
db.testcollection.insertOne({name: "test", timestamp: new Date()})

# Check replication on secondary
db.getMongo().setReadPref("secondary")
db.testcollection.find()

Test automatic failover by stopping the primary:

# On primary server
sudo systemctl stop mongod

# Check replica set status from secondary
rs.status()

# Verify new primary election occurred

Common Issues and Troubleshooting

Here are frequent problems and their solutions:

Issue: Members stuck in STARTUP or STARTUP2 state

# Check MongoDB logs
sudo tail -f /var/log/mongodb/mongod.log

# Common causes: network connectivity, clock synchronization, insufficient resources
# Verify time synchronization
sudo systemctl status systemd-timesyncd
timedatectl status

Issue: “not authorized” errors after enabling authentication

# Ensure keyfile permissions are correct
ls -la /etc/mongod-keyfile
# Should show: -r-------- 1 mongodb mongodb

# Verify keyfile contents are identical across all nodes
sudo md5sum /etc/mongod-keyfile

Issue: High replication lag

# Check replication lag
rs.printSecondaryReplicationInfo()

# Monitor oplog window
db.oplog.rs.find().limit(1).sort({$natural:-1})
db.oplog.rs.find().limit(1).sort({$natural:1})

Issue: Split-brain scenarios

  • Always use odd numbers of voting members (3, 5, 7)
  • Distribute nodes across different availability zones
  • Consider using an arbiter for cost-effective odd-member setups

Monitoring and Maintenance

Set up monitoring to track replica set health and performance:

# Enable profiling for slow operations
mongosh -u admin
db.setProfilingLevel(1, {slowms: 100})

# Monitor replica set metrics
db.serverStatus().repl
db.printReplicationInfo()
db.printSecondaryReplicationInfo()

Regular maintenance tasks include:

  • Monitor oplog size and adjust as needed
  • Perform regular backups using mongodump or filesystem snapshots
  • Monitor disk usage and plan for growth
  • Keep MongoDB versions updated across all members
  • Test disaster recovery procedures regularly

Real-World Use Cases and Applications

MongoDB replica sets excel in various scenarios:

E-commerce Applications: Product catalogs benefit from read scaling across secondaries while maintaining consistency for inventory updates through the primary.

Content Management Systems: Blog platforms and news sites can serve read-heavy traffic from secondaries while ensuring editorial changes propagate consistently.

IoT Data Collection: Time-series data from sensors can be written to the primary while analytics queries run against secondaries without impacting write performance.

Geographically Distributed Applications: Place replica set members in different regions to reduce latency for local reads while maintaining data consistency.

Comparison with Alternative Solutions

Solution Consistency Availability Partition Tolerance Complexity
MongoDB Replica Set Strong High Yes Medium
MySQL Master-Slave Eventual Medium Limited Medium
PostgreSQL Streaming Strong High Limited High
MongoDB Sharding Strong Very High Yes High

MongoDB replica sets provide an excellent balance of consistency, availability, and operational simplicity compared to traditional SQL replication solutions.

For applications requiring high availability and data durability, a properly configured MongoDB replica set on Ubuntu 24 provides robust data protection and automatic failover capabilities. The setup process, while initially complex, results in a self-healing database architecture that can handle various failure scenarios. Remember to test your configuration thoroughly and implement proper monitoring to ensure optimal performance in production environments.

For hosting your MongoDB replica set infrastructure, consider VPS solutions for development environments or dedicated servers for production deployments requiring consistent performance and isolation.

Additional resources for deeper understanding include the official MongoDB replication documentation and the replica set deployment guide.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked