{"id":21460,"date":"2015-06-22T18:13:36","date_gmt":"2015-06-22T12:43:36","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=21460"},"modified":"2016-08-30T10:51:10","modified_gmt":"2016-08-30T05:21:10","slug":"how-to-setup-replica-sets-in-mongo-db-aws-ec2","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/how-to-setup-replica-sets-in-mongo-db-aws-ec2\/","title":{"rendered":"How to Setup Replica Sets in Mongo DB (AWS EC2)"},"content":{"rendered":"<p><a title=\"MEAN stack development\" href=\"http:\/\/www.tothenew.com\/mean-stack-web-development-consulting\">MongoDB<\/a> is a popular NoSQL database that stores data in JSON like documents dynamic schemas instead of storing your data in tables and rows as you do with a relational database.<\/p>\n<p>In this blog we will setup Mongo DB replication on single node to demonstrate high availability and failover mechanism.<\/p>\n<h3>What is a MongoDB Replica Set ?<\/h3>\n<p>We can achieve high availability and failover with the help of Replica Sets in MongoDB. In this configuration application\/client can read and write data from\/to primary node. The changes in primary node are replicated to secondary node using oplog (operations log). The secondary node can be used for read only operations depending on the use case. The main <a href=\"http:\/\/www.tothenew.com\/blog\/load-blancing-of-amazon-rds-read-replica\/\">advantage of replica<\/a> set is that it offers automatic failover mechanism in case primary node goes down.<\/p>\n<h3>Replica Set Components:<\/h3>\n<p>1. Primary Members: By default, all read, write transactions are made on the primary node<br \/>\n2. Secondary Members: Any changes made on primary nodes are replicated to secondary nodes using oplogs.<br \/>\n3. Arbitar Members: An arbitar is an optional member of the replica set that does not take part in replication. It only takes part in the selection process of new primary.<br \/>\n4. Selection Process: In case a primary node goes down, the automatic selection process takes place between remaining secondary nodes. And if number of secondary nodes are even, arbitar member acts as a tie-broker to ensure decision is reached.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21464\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Introduction_1.png\" alt=\"Introduction_1\" width=\"553\" height=\"344\" \/><br \/>\n<b><\/b><\/p>\n<p><span style=\"color: red; font-size: small;\"><br \/>\nNote:<br \/>\n1. Data on secondary node can be outdated as replication between primary and secondary nodes is asynchronous. So this feature should be carefully enabled in production environment.<br \/>\n2. This kind of implementation requires code level changes to redirect read queries to secondary nodes and write queries to primary node.<br \/>\n<\/span><\/p>\n<p><strong>1. Setup Replica Sets on Single EC2 Instance<\/strong><\/p>\n<p>For setting up test environment in few clicks, I am using AWS EC2 (Amazon Linux) for demonstration purpose. You can download Mongo package from MongoDB official website. Once you have MongoDB downloaded, you need to create a data folder for each mongo instances. I&#8217;m on a Amazon Linux (t2.micro) and created mongo-data0, mongo-data1 and mongo-data2.<\/p>\n<p><span style=\"color: red; font-size: small;\">Note: In production environment it is not recommended to run multiple Replica Set&#8217;s on a single machine with oplogSize 50, I am doing this only for demonstration purpose.\u00a0<\/span><\/p>\n<p>You also need to run each instance on a separate port so I chose 27009, 27010 and 27011. I started the three instances as follows (in three separate Terminals):<\/p>\n<p>[js]mongod &#8211;dbpath mongo-data0 &#8211;port 27009 &#8211;rest &#8211;replSet mongo-data &#8211;logpath log.mongo-data0 &#8211;fork &#8211;alogappend &#8211;smallfiles &#8211;oplogSize 50<br \/>\nmongod &#8211;dbpath mongo-data1 &#8211;port 27010 &#8211;rest &#8211;replSet mongo-data &#8211;logpath log.mongo-data1&#8211;fork &#8211;alogappend &#8211;smallfiles &#8211;oplogSize 50<br \/>\nmongod &#8211;dbpath mongo-data2 &#8211;port 27010 &#8211;rest &#8211;replSet mongo-data &#8211;logpath log.mongo-data2 &#8211;fork &#8211;alogappend &#8211;smallfiles &#8211;oplogSize 50 [\/js]<\/p>\n<p><strong>Command Description:<\/strong><\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21497\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Command-Discription.png\" alt=\"Command Discription\" width=\"655\" height=\"551\" \/><\/p>\n<p>Commands to setup replica set&#8217;s on single machines:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21502\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/replicaset_3.png\" alt=\"replicaset_3\" width=\"1265\" height=\"129\" \/><\/p>\n<p>Check the list of running mongo processes, using ps -ef | grep mongo (shown below):<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21503\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_Replica_Set_Processes_4.png\" alt=\"Mongo_Replica_Set_Processes_4\" width=\"1299\" height=\"166\" \/><\/p>\n<p><strong>2. Access Replica Sets<\/strong><br \/>\nIf you want you can add each node to have a separate name, to do so you can add the following entry to \/etc\/hosts:<br \/>\n127.0.0.1 mongo1 mongo2 mongo3<br \/>\nOnce done you are ready to connect to Mongo DB Replica Set. You can start accessing replica set by using the command below in your terminal<\/p>\n<p>[js]mongo &#8211;port 20017<br \/>\n&gt; rs.initiate()<br \/>\n&gt; rs.add(&quot;shard1.neerajg.in:27010&quot;)<br \/>\n&gt; rs.add(&quot;shard1.neerajg.in:27011&quot;)[\/js]<\/p>\n<p>Note: In case of production environment, you will be running replica set&#8217;s on separate hosts, you can also add them using above mentioned command. For example:<\/p>\n<p>[js]&gt;rs.add(\u201chost1.neerajg.in27010\u201d)<br \/>\n&gt;rs.add(\u201chost2.neerajg.in:27010\u201d)[\/js]<\/p>\n<p>Access Primary Replica Set (running on port 27009):<br \/>\na. Initiate Replica Set on Primary mongo instance:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21505\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_Initiate_replica_set5.png\" alt=\"Mongo_Initiate_replica_set5\" width=\"1299\" height=\"480\" \/><\/p>\n<p>b. Check the status of primary mongo instance again<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21506\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_replica_set_primary6.png\" alt=\"Mongo_replica_set_primary6\" width=\"925\" height=\"434\" \/><\/p>\n<p>c. Add Secondary Replica Sets:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21507\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_replica_set_add_shard7.png\" alt=\"Mongo_replica_set_add_shard7\" width=\"665\" height=\"75\" \/><\/p>\n<p>d. Print Replication Info:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21508\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/print_replication_info8.png\" alt=\"print_replication_info8\" width=\"613\" height=\"161\" \/><\/p>\n<p><strong>3. Add data to primary node:<\/strong><\/p>\n<p>At this point we can add objects to the database and they&#8217;ll be replicated to the other instances &#8211; and you can read from the primary or the slaves.<\/p>\n<p>[js]db.people.save( { name : &quot;Neeraj&quot;, age: 26, emailid: &quot;neeraj.gupta@tothenew.com&quot; } )<br \/>\n db.people.find() [\/js]<\/p>\n<p>a. Add data to primary mongo instance using the below mentioned commands:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21509\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Add_Data_Primary9.png\" alt=\"Add_Data_Primary9\" width=\"1134\" height=\"189\" \/><\/p>\n<p>You can try accessing secondary node and read data using the below mentioned commands.<\/p>\n<p>[js]mongo &#8211;host mongo2 &#8211;port 22017<br \/>\nrs.slaveOk()<br \/>\ndb.people.find()[\/js]<\/p>\n<p>Access Secondary Replica Set running on port 27010:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21511\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo-Replica-Set-Seconday1_10a.png\" alt=\"Mongo-Replica-Set-Seconday1_10a\" width=\"1299\" height=\"321\" \/><\/p>\n<p>Access Secondary Replica Set running on port 27011:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21512\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_replica_set_Seconday2_10b.png\" alt=\"Mongo_replica_set_Seconday2_10b\" width=\"1299\" height=\"313\" \/><\/p>\n<p><strong>4. Check the log files:<\/strong><\/p>\n<p>Accessing the log files:<\/p>\n<p>a. Primary Replica Logs (27009):<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21513\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_Primary_replica_logs_11.png\" alt=\"Mongo_Primary_replica_logs_11\" width=\"1299\" height=\"36\" \/><\/p>\n<p>b. Secondary Replica Logs (27010):<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21514\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mogno_replica_seconday_log12.png\" alt=\"Mogno_replica_seconday_log12\" width=\"1300\" height=\"200\" \/><\/p>\n<p>5. Test failover capabilities:<\/p>\n<p>Now to test failover capabities, do the following:<\/p>\n<p>a. You can either terminate terminal running primary mongodb node or extract process id using the below mentioned command and kill process.<\/p>\n<p>[js]ps -ef | grep mongo<\/p>\n<p>kill PID [\/js]<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21515\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_Kill_Primary13.png\" alt=\"Mongo_Kill_Primary13\" width=\"1300\" height=\"485\" \/><\/p>\n<p>b. During this activity kindly observe the other two terminals. It will show messages like transition to primary complete.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21519\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/secondary_to_primary141.png\" alt=\"secondary_to_primary14\" width=\"1298\" height=\"179\" \/><\/p>\n<p>c. After few seconds, try to access the remaining two replica sets running on port 27010 and 27011. One of them will be primary and other will be secondary.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21520\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_Secondary_to_Primary_Example15.png\" alt=\"Mongo_Secondary_to_Primary_Example15\" width=\"1284\" height=\"445\" \/><\/p>\n<p>d. Operations supported:<\/p>\n<p>i. Primary Mode: Read, write (to validate this try adding new content to the database by using below mentioned commands):<\/p>\n<p>[js] db.people.save( { name : &quot;Amit&quot;, age: 26, emailid: &quot;ankit.kumar@tothenew.com&quot; } ) [\/js]<\/p>\n<p>Above command will run successfully and add new content to the db (as shown in the above screenshot)<\/p>\n<p>[js]db.people.find() [\/js]<\/p>\n<p>Above command will retrieve all the data stored in people collection<br \/>\nii. Secondary Mode: Read Only (to validate this try adding new content to the database by using the below mentioned commands):<\/p>\n<p>[js] db.people.save( { name : &quot;Amit&quot;, age: 26, emailid: &quot;ankit.kumar@tothenew.com&quot; } ) [\/js]<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-21521\" src=\"\/blog\/wp-ttn-blog\/uploads\/2015\/06\/Mongo_replica_set_secondary_write_error16.png\" alt=\"Mongo_replica_set_secondary_write_error16\" width=\"1300\" height=\"317\" \/><\/p>\n<p><span style=\"color: red; font-size: small;\"><b>NOTE: Above command will throw error messages, as seconday node runs in read only mode.<\/b><\/span><\/p>\n<p>[js]db.people.find() [\/js]<\/p>\n<p>Above command will retrieve all data stored in people collection<\/p>\n","protected":false},"excerpt":{"rendered":"<p>MongoDB is a popular NoSQL database that stores data in JSON like documents dynamic schemas instead of storing your data in tables and rows as you do with a relational database. In this blog we will setup Mongo DB replication on single node to demonstrate high availability and failover mechanism. What is a MongoDB Replica [&hellip;]<\/p>\n","protected":false},"author":216,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":54},"categories":[1174],"tags":[248,1900,1901,1902],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/21460"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/216"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=21460"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/21460\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=21460"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=21460"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=21460"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}