Introducing Dragonfly Cloud! Learn More

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

Answer

Setting up a MongoDB cluster, also known as a Replica Set, on Ubuntu involves several steps that ensure redundancy and high availability of your database. Below is a comprehensive guide to achieve this setup.

Prerequisites

  • Three or more Ubuntu servers (version 18.04 or later) for the members of the replica set.
  • Sudo privileges on each server.

Step 1: Install MongoDB

On all your Ubuntu servers, install MongoDB. MongoDB's official package provides the most up-to-date version and is recommended over the default Ubuntu packages.

  1. Import the MongoDB public GPG key:
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
  1. Create a list file for MongoDB:
echo \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -sc)/mongodb-org/4.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list
  1. Update the local package database:
sudo apt-get update
  1. Install MongoDB:
sudo apt-get install -y mongodb-org

Repeat these steps on all the servers.

Step 2: Configure the MongoDB Replica Set

On each server, edit the MongoDB configuration file, /etc/mongod.conf, to enable replication and specify the replica set name.

  1. Open the configuration file:
sudo nano /etc/mongod.conf
  1. In the net section, uncomment the bindIp line and replace 127.0.0.1 with 0.0.0.0 to allow connections from other servers.

  2. In the replication section, add:

replication: replSetName: \"rs0\"

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

  1. Restart MongoDB to apply the changes:
sudo systemctl restart mongod

Step 3: Initialize the Replica Set

Choose one server to act as the primary node and connect to the MongoDB shell on that server:

mongo

In the Mongo shell, initialize the replica set:

rs.initiate()

After initiation, add the other servers as members of the replica set:

rs.add(\"server2_ip:27017\") rs.add(\"server3_ip:27017\")

Replace server2_ip and server3_ip with the actual IP addresses of your other servers.

Step 4: Verify the Replica Set Configuration

To verify that the replica set has been configured correctly, use the following command in the Mongo shell:

rs.status()

This command will display the status of the replica set, including the primary and secondary nodes.

Conclusion

You have now successfully set up a MongoDB replica set on Ubuntu. This setup ensures that your MongoDB deployment is highly available and can withstand server failures.

Was this content helpful?

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

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.