Skip to content

How to Setup MongoDB Replication On Ubuntu 20.04

homepage-banner

MongoDB is a free and open-source NoSQL database system developed by MongoDB Inc. It is document-oriented, using JSON-like documents with optional schemas instead of tables and rows. MongoDB provides scalability and flexibility, allowing you to store and retrieve large volumes of data.

A MongoDB replica set is a group of processes used for redundancy and high availability. It enables you to distribute data across multiple database servers. In a replica set, one node is a primary node that receives all write operations, while all other nodes are secondary nodes that perform read operations.

This post will show you how to set up a three-node MongoDB replication on Ubuntu 20.04.

Getting Started

To begin, you need to set up hostname resolution on each node to enable communication between them using hostnames. To do this, edit the /etc/hosts file on each node and add the following lines:

vim /etc/hosts

Next, add the following lines to the file:

node1-ip-address mongo-node1 node2-ip-address mongo-node2 node3-ip-address mongo-node3

Save and close the file, then install all required dependencies on every node:

apt-get install dirmngr gnupg apt-transport-https ca-certificates software-properties-common -y

After installing all dependencies, you can proceed to the next step.

Installing MongoDB Server on All Nodes

To begin, you will need to install MongoDB server on all nodes. By default, the latest version of MongoDB is not included in the Ubuntu default repository, so you will need to add the MongoDB repository on each node.

To do so, run the following command to add the GPG key and MongoDB repository:

wget -qO - <https://www.mongodb.org/static/pgp/server-4.4.asc> | apt-key add - add-apt-repository 'deb [arch=amd64] <https://repo.mongodb.org/apt/ubuntu> focal/mongodb-org/4.4 multiverse'

Next, update the repository and install MongoDB with the following command:

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

Once MongoDB is installed, start the MongoDB service and enable it to start at system reboot:

systemctl start mongod systemctl enable mongod

At this point, MongoDB is installed on all nodes.

Creating an Admin User on the Primary Node

To authenticate MongoDB, you need to create an admin user on the primary node.

On the mongo-node1, connect to MongoDB using the following command:

mongo

Once connected, switch to the admin database:

use admin

Next, create a user named mongo-admin and set a password:

db.createUser({user: "mongo-admin", pwd: "password", roles:[{role: "root", db: "admin"}]})

Finally, exit from MongoDB:

exit

Configure Primary Node

To configure the primary node for MongoDB, you will need to create a key file.

On mongo-node1, run the following command to create a key file and set proper permissions and ownership:

openssl rand -base64 756 > /opt/mongo-keyfile
chmod 400 /opt/mongo-keyfile
chown mongodb:mongodb /opt/mongo-keyfile

Next, copy the /opt/mongo-keyfile to the second and third nodes with the following commands:

scp /opt/mongo-keyfile root@mongo-node2:/opt/
scp /opt/mongo-keyfile root@mongo-node3:/opt/

Then, edit the MongoDB main configuration file on mongo-node1:

vim /etc/mongod.conf

Add or change the following lines:

net:
  port: 27017
  bindIp: 127.0.0.1,node1-ip-address
security:
  keyFile: /opt/mongo-keyfile
replication:
  replSetName: "replica01"

Save and close the file when finished.

Configure Second and Third Node

Next, you need to configure the second and third MongoDB nodes.

On mongo-node2, edit the MongoDB main configuration file:

vim /etc/mongod.conf

Add/change the following lines:

net:
  port: 27017
  bindIp: 127.0.0.1,node2-ip-address
security:
  keyFile: /opt/mongo-keyfile
replication:
  replSetName: "replica01"

Save and close the file. Then, set proper ownership and permissions for the mongo-key file:

chmod 400 /opt/mongo-keyfile
chown mongodb:mongodb /opt/mongo-keyfile

On mongo-node3, edit the MongoDB main configuration file:

vim /etc/mongod.conf

Add/change the following lines:

net:
  port: 27017
  bindIp: 127.0.0.1,node3-ip-address
security:
  keyFile: /opt/mongo-keyfile
replication:
  replSetName: "replica01"

Save and close the file. Then, set proper ownership and permissions for the mongo-key file:

chmod 400 /opt/mongo-keyfile
chown mongodb:mongodb /opt/mongo-keyfile

At this point, all nodes are configured.

Restart MongoDB Service on All Nodes

Next, you need to restart the MongoDB service on all nodes one by one.

On mongo-node1, restart the MongoDB service using the following command:

systemctl restart mongod

On mongo-node2, restart the MongoDB service using the following command:

systemctl restart mongod

On mongo-node3, restart the MongoDB service using the following command:

systemctl restart mongod

Start Replication and Add Members

Next, you need to start the replication on the primary node and add other nodes as members.

On mongo-node1, connect to Mongo with admin user:

mongo -u mongo-admin -p --authenticationDatabase admin

Next, initiate the replica set with the following command:

> rs.initiate()

Output:

{ "info2" : "no configuration specified. Using a default configuration for the set", "me" : "node1-ip-address:27017", "ok" : 1 }

Next, add mongo-node2 as a member with the following command:

replica01:PRIMARY> rs.add("mongo-node2")

Output:

{ "ok" : 1, "$clusterTime" : { "clusterTime" : Timestamp(1619609840, 1), "signature" : { "hash" : BinData(0,"zuOCVWO9Nv7q+4sceYaXd9x/7kw="), "keyId" : NumberLong("6956170826928357380") } }, "operationTime" : Timestamp(1619609840, 1) }

Next, add mongo-node3 as a member with the following command:

replica01:PRIMARY> rs.add("mongo-node3")

Output:

{ "ok" : 1, "$clusterTime" : { "clusterTime" : Timestamp(1619609869, 1), "signature" : { "hash" : BinData(0,"FIUN74frDell2yfOAN6qzZAIljE="), "keyId" : NumberLong("6956170826928357380") } }, "operationTime" : Timestamp(1619609869, 1) }

You can also check the status of all nodes with the following command:

rs.status()

Test Replication

At this point, replication is configured on the primary node. Now, it’s time to test whether the replication is working or not.

On mongo-node1, create a database and add some values.

mongo -u mongo-admin -p --authenticationDatabase admin
replica01:PRIMARY> use exampleDB
replica01:PRIMARY> for (var i = 0; i <= 10; i++) db.exampleCollection.insert( { x : i } )

Output:

WriteResult({ "nInserted" : 1 })

Now, check your database with the following command:

replica01:PRIMARY> show dbs

Output:

admin 0.000GB config 0.000GB exampleDB 0.000GB local 0.000GB

On mongo-node2, connect to the Mongo shell with the following command:

mongo -u mongo-admin -p --authenticationDatabase admin

Once connected, run the following command to enable secondary member read operations on a per-connection basis:

replica01:SECONDARY> db.getMongo().setSecondaryOk()

Next, change the database to exampleDB:

replica01:SECONDARY> use exampleDB

Next, run the following command to show all documents:

replica01:SECONDARY> db.exampleCollection.find()

If replication is working, you’ll see a list of the sample documents we created on the primary host:

{ "_id" : ObjectId("60894e33213113780d5fef3b"), "x" : 0 }
{ "_id" : ObjectId("60894e33213113780d5fef3c"), "x" : 1 }
{ "_id" : ObjectId("60894e33213113780d5fef3d"), "x" : 2 }
{ "_id" : ObjectId("60894e33213113780d5fef40"), "x" : 5 }
{ "_id" : ObjectId("60894e33213113780d5fef42"), "x" : 7 }
{ "_id" : ObjectId("60894e33213113780d5fef3f"), "x" : 4 }
{ "_id" : ObjectId("60894e33213113780d5fef43"), "x" : 8 }
{ "_id" : ObjectId("60894e33213113780d5fef44"), "x" : 9 }
{ "_id" : ObjectId("60894e33213113780d5fef3e"), "x" : 3 }
{ "_id" : ObjectId("60894e33213113780d5fef45"), "x" : 10 }
{ "_id" : ObjectId("60894e33213113780d5fef41"), "x" : 6 }

Conclusion

In the above guide, you learned how to configure MongoDB replication on Ubuntu 20.04. You can now add more members to the replica set. I hope this guide will help you distribute data across many database servers in the production environment.

Leave a message