How To MongoDB Replica Sets

MongoDB allows you to set up Replica Sets (a sort of advanced Master/Slave) very easily, the most common use is to provide data redundancy and automated failover.

A Replica Sets consists of at least 3 members, either 2 full nodes and 1 arbiter, either 3 full nodes. So with 3 members, you'll have 1 primary node and 2 secondary nodes (or 1 primary, 1 secondary and 1 arbiter).

I'm using MongoDB version 2.2.1.


From Mongodb docs.

$ sudo apt-key adv --keyserver --recv 7F0CEB10
$ echo "deb dist 10gen" | sudo tee -a /etc/apt/sources.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen


Fire up a mongo console and add an admin user:

$ mongo

Enter the following commands:

use admin;
db.addUser("username", "password")

Create the key file, wich is just a string.

$ echo "MySuperKey" > mykeyfile

The key file must be owned by the user who run the daemon, mongodb or root if you run mongod yourself.

$ chmod 700 mykeyfile
$ sudo chown mongodb:mongodb mykeyfile

Also don't forget to change the dbpath config parameter.

Setting up members

You can manage mongod configuation in the /etc/mongodb.conf config file or with command line options.

bind_ip =
rest = true
keyFile = /path/to/keyfile
replSet = youreplicasetname

Start a mongodb instance:

$ ./mongod --rest --replSet replsetname --dbpath /path/to/db --keyFile /home/thomas/mykeyfile --bind_ip --port 30018

Initiate the replica set

Fire up a mongo console.

$ mongo

Log in:

use admin;
db.auth("username", "password")

Next, you can initiate the replicaSet.


You can add a higher priority to a member, so it'll be elected primary where all the members are up.

cfg = {
    _id : "topicaset2",
    members : [
        {_id : 0, host : "", "priority": 2},
        {_id : 1, host : ""},
// Add an arbiter

// Add a member

// Removing a member

You should follow me on Twitter

Share this article

Tip with Bitcoin

Tip me with Bitcoin and vote for this post!


Leave a comment

© Thomas Sileo. Powered by Pelican and hosted by DigitalOcean.