MongoDB is an open-source document database and leading NoSQL database,and if we are using it in a production account we should deploy it in a Replica Set.
Here is a quick rundown on how to implement that on a AWS EC2
Replication:
Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup.
Step1: copy files for backup
Before proceeding we need to take the backup of hosts file and mongod.cnf file for an roll back process.
copy the hosts file and mongod.cnf and save in the location you wish.
cp /etc/hosts /home/ajay/host_modifycp /etc/mongod.cnf /home/ajay/mongod_befor.cnf
Step2: /etc/hosts entry
To run a replica set more probably an cluster setup, will add the server IP’s in /etc/hosts files
Vi /etc/hosts172.31.92.67 mongo1
172.31.92.100 mongo2
172.31.84.138 mongo3
Step3: Configure the firewalls
since our mongod uses port 27017 , lets enable the port in the firewall ( here I used ubuntu os)
sudo ufw enablesudo ufw allow 27017
run the command in all the three nodes we subjected for replication.
Step4: Configure the replicaset:
Replica set can have only one primary node. Replica sets have an attribute of fail over automatically, so if one of the members becomes unavailable, a new primary host is elected and your data is still accessible. That means, when a primary replica fails,the replica set automatically conducts an election process to determine which secondary should become the primary.
Lets edit the mongod.cnf file for replica set.
net:
port: 27017
bindIp: 172.31.92.67 #Bind the ip of your local server(private ip)
Now, lets move to enable the replication inside the mongod.cnf
replication:
replSetName: “replicamongo”
The value “replicamongo” is the name we’re using for our replica set for this tutorial, you can use a different naming convention if you like.
Once done all changes we have to restart the mongod services.
Step 5 : login mongo services
mongo private ip
Once done, lets enable the replication running the following command
rs.initiate()
Its saying secondary.type enter it will be changed to primary node
we can add other nodes in primary server:
rs.add(“secondry server ip1”)rs.add(“secondry server ip2)
Now check the replica status:
rs.status()
After login Mongodb secondary servers run the commnad
rs.slavOk()
check the slave status
rs.status()