How to configure a MongoDB replica set (local machine)

This post will guide you through the steps to set up a local replica set with two members and one arbiter.

In a production environment the steps must be almost the same except that instead of starting three local MongoDB instances in different ports you would start an instance of MongoDB on each server with its own configuration file.

This guide assumes that you have installed MongoDB with the most basic linux command:

sudo apt-get install mongodb

Once installed, please follow these steps:

  1. Create a folder to store all MongoDB-related data
mkdir /data
  1. Create a folder for each MongoDB instance (in production environments, ideally, each server will run one instance)
mkdir /data/r0s1
mkdir /data/r0s2
mkdir /data/r0s3
  1. Open three separate terminals and run one instance of MongoDB making sure you set a different port and its corresponding dbpath for each one of them
mongod --replSet rs0 --port 27021 --dbpath /data/r0s1
mongod --replSet rs0 --port 27022 --dbpath /data/r0s2
mongod --replSet rs0 --port 27023 --dbpath /data/r0s3
  1. Connect to the first instance like this
mongo --host 127.0.0.1:27021
  1. Type the config into an object and hit enter, the replica set name I am using is rs0 and the two members are the ones that will store data (arbiter shouldn’t be included here)
myConfig = {"_id":"rs0",
    members:[
        { _id:0, host: "127.0.0.1:27021" },
        { _id:1, host: "127.0.0.1:27022" }
    ]
}
  1. Initiate the replica set
rs.initiate(myConfig)
  1. Add the arbiter
rs.addArb("127.0.0.1:27023")
  1. Check the status of the replica set. You should have a JSON object with an array called members, this array should contain three objects (one for each MongoDB instance conforming the replica set), the property health set to 1 means everything is OK
rs.status()
  1. Test the replica set by creating a database
use testReplication
  1. Insert a new document. The collection name will be the same as the database name (unless you created a new collection)
db.testReplication.insert({testField:"Hello World!"})
  1. Retrieve the data you just entered
db.testReplication.find().pretty()

You should see something similar to this:

{
    "_id" : ObjectId("5f903ffdd9a912e7c8eff756"),
    "testField" : "Hello World!"
}

That’s it!

Now, you should remember that by default you can’t query any secondary servers (it’s possible, you just need to specify it in the configuration). Whenever the primary instance stops working the arbiter will decide which secondary instance will become the new primary instance, it will make the switch. Whenever the server is back online it will remain as a secondary instance and will synchronize with the primary.