Hello, I am an Engineering Manager at Facebook with 13+ years in Ad Technology, Natural Language Processing and Data mining. (Learn More)
by Pravin Paratey

Setting up Replica sets in MongoDB

Are you ready to set up replica sets in under 5 minutes? Set your stopwatches. Ready, set, go!

Minute 0: Overview of the servers

We are going to use replica sets consisting of 3 nodes which looks something like this,

replica set with 3 nodes

Minute 1: Downloading and installing MongoDB

The latest instructions to download and install Mongo can be found here. For me, running on a CentOS machine, all I had to do was add the 10gen repository, followed by a sudo yum install mongo-10gen mongo-10gen-server. To add the 10gen repository, adding the following lines to /etc/yum.repos.d/10gen.repo

[10gen]
name=10gen Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64
gpgcheck=0
$ sudo yum install mongo-10gen mongo-10gen-server

Do this on all your servers.

Minute 2: Editing the configuration file

Next, edit the configuration file which is present at /etc/mongodb.conf and add the two lines to it

bind_ip = 192.168.1.1 # Public or Internal IP of the server. This will change with each server.
replSet = london # This string should be the same on all 3 servers

Again, this should be done on all servers.

Minute 3: Starting Mongo

Start Mongo on all servers by running

$ sudo service mongod start

On Debian systems, you will have to run the mongodb service instead,

$ sudo service mongodb start

Minute 4: Adding nodes to the primary

Pick any machine and enter the Mongo CLI by typing mongo IP.Of.Server.One. This will be your primary machine (until the cluster decides to elect another as its primary).

Next, run rs.initiate() on the machine. This will initialise the node to use replica sets. Then run rs.add("IP.Of.Server.Two") and rs.add("IP.Of.Server.Three") to add the other two nodes to the replica set.

$ mongo IP.Of.Server.One
> rs.initiate();
> rs.add("IP.Of.Server.Two");
> rs.add("IP.Of.Server.Three");
> rs.status();

That’s it! We’re done. That was easy, wasn’t it?

Removing a member of the replica set

Removing a node is as easy as typing

> rs.remove("IP.Of.Server.To.Remove:port")