Dragonfly

Question: How do you set up a MongoDB replica set on Ubuntu?

Answer

Setting up a MongoDB replica set on Ubuntu involves several steps, including installing MongoDB, configuring the replica set, and initializing it. Below is a comprehensive guide to get you started.

Step 1: Install MongoDB

First, update your Ubuntu's package database and install MongoDB.

sudo apt-get update
sudo apt-get install -y mongodb-org

Ensure MongoDB is started and enabled to start on boot:

sudo systemctl start mongod
sudo systemctl enable mongod

Step 2: Configure MongoDB for Replica Set

Edit the MongoDB configuration file, usually found at /etc/mongod.conf, to enable replica sets. You'll need to add or modify the replication section:

replication:
  replSetName: \"rs0\"

Here, rs0 is the name of your replica set. You can choose any name you prefer.

After making these changes, restart MongoDB:

sudo systemctl restart mongod

Step 3: Initialize the Replica Set

On the primary server, access the MongoDB shell:

mongo

In the MongoDB shell, initialize the replica set:

rs.initiate({
  _id : \"rs0\",
  members: [
    { _id: 0, host: \"your_primary_server_ip:27017\" }
  ]
})

Replace \"your_primary_server_ip\" with the actual IP address of your server. This command initializes the replica set with a single member (the primary server).

Step 4: Add Additional Members to the Replica Set

If you have additional servers you want to include in the replica set as secondary nodes, use the rs.add() command:

rs.add(\"your_secondary_server_ip:27017\")

Replace \"your_secondary_server_ip\" with the IP address of your secondary server.

Repeat this step for each secondary server you wish to add to the replica set.

Step 5: Verify Replica Set Configuration

To verify that your replica set is configured correctly and all members have been added, use the following command:

rs.status()

This command provides detailed information about the replica set configuration and status of each member.

Conclusion

You now have a MongoDB replica set running on Ubuntu. This setup enhances your database's availability and fault tolerance. Keep in mind that managing a replica set involves regular maintenance tasks such as monitoring performance, managing backups, and handling failovers.

Was this content helpful?

Other Common MongoDB Performance Questions (and Answers)

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost