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.

Installing

From Mongodb docs.

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
$ echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | sudo tee -a /etc/apt/sources.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen

Security

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 = 0.0.0.0
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 0.0.0.0 --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.

rs.initiate();
rs.status();

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 : "serverA.com", "priority": 2},
        {_id : 1, host : "serverB.com"},
    ]
};
rs.initiate(cfg);
// Add an arbiter
rs.addArb("host:port")

// Add a member
rs.add("host:port")

// Removing a member
rs.remove("host:port")

You should follow me on Twitter

Share this article

Tip with Bitcoin

Tip me with Bitcoin and vote for this post!

1FKdaZ75Ck8Bfc3LgQ8cKA8W7B86fzZBe2

Leave a comment

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