How to Setup MongoDB Replication using Replica Sets on Ubuntu 16.04

ubuntu-mongo

MongoDB is a free and open-source cross-platform document-oriented database program. MongoDB is a NoSQL database program and uses JSON-like documents with schemas. MongoDB supports many NoSQL database types.

  • Document databases
  • Graph stores
  • Key-value stores
  • Wide-column stores

To know more about MongoDB visit www.mongodb.com

In this article we will learn how to replicate MongoDB data on different servers. A replica set in MongoDB is a group of mongod processes that maintain the same data set, replica sets provide redundancy and high availability.

Perquisites: MongoDB Server

Note: – If you want to see the Installation of MongoDB Server, click on below Link:

https://www.cloudjojo.com/how-to-install-mongodb-server-on-ubuntu-16-04/

Step 1. Login to Master server & stop the MongoDB.
# service mongodb stop

Step 2. Edit & Modify the Configuration file of MongoDB.

vim /etc/mongodb.conf
#bind_ip = 127.0.0.1
port = 27017

# Add a below line at the end of the file.

replSet = rs0

Step 3. Edit Host file by specifying the IP & Hostname of Secondary Server .

vim /etc/hosts
54.219.175.18     ip-172-31-7-104

Step 4. Start MongoDB Server.

# service mongodb start

Step 5. Login to Secondary Server & stop the MongoDB.

# service mongodb stop

Step 6. Edit & Modify the Configuration file of MongoDB.

# vim /etc/mongodb.conf
#bind_ip = 127.0.0.1
port = 27017

# Add a below line at the end of the file.

replSet = rs0

Step 7. Edit Host file by specifying the IP & Hostname of Master Server .

vim /etc/hosts
54.145.251.84     ip-172-31-20-123

Step 8. Start MongoDB Server.

# service mongodb start

Step 9. Open MongoDB shell on Master Server & add the second server which will become the Secondary.

# mongo
> rs.initiate()
> rs.add('ip-172-31-7-104:27017')

Step 10. Test a Secondary Server by adding a document to a Master Server.

> db.foo.save({_id:1, value:'hello world'})
> db.setSlaveOk()
> db.foo.find()

This will return:

{ "_id" : 1, "value" : "hello world" }

Step 11. Login to Secondary Server & execute below command.

# mongo
> db.foo.find()

# Output will be:

{ "_id" : 1, "value" : "hello world" }

Step 12. You can view the config of connected nodes by using below command.

> rs.config()

Step 13. You can also view the status of connected nodes by using below command.

> rs.status()

Step 14. You can Remove nodes by using below command.

> rs.remove("HostnameOfNodeServer")