Sunday, June 14, 2015

A MongoDB Cluster with Replica Sets Tutorial

Because I've already covered the basic idea behind replica sets in the past, this is going to be a straightforward guide for implementing a replica sets into an existing MongoDB cluster. Let's get right to it.

Prerequisites: You'll want to be familiar with setting up VirtualBox with Vagrant and MongoDB Sharding. This guide was written for Mac OS X users.

The Basic Architecture

We're going to keep things simple and set up a cluster with one primary node, and two secondaries.

Provisioning Our MongoDB Instances

To spin up the two MongoDB instances, we're going to be cloning a repo that contains a Vagrantfile and Ansible playbook that allows us to provision virtual machines with mongod installed. This is the only step of the tutorial we're going to automate. The rest of the steps will need to be performed manually, in order to give you an intimate understanding of how replica sets work.

# clone the repo
git clone mongocluster
cd mongocluster

vi Vagrantfile

We're using this repo because it comes with an Ansible playbook we'll be using to install MongoDB. To set up our cluster, you'll want to update your Vagrantfile with the following content:

Setting Up the Instances

Carry out the following steps on each server:

# ssh in
vagrant ssh primary

# stop mongod
sudo service mongodb stop

# create a metadata directory
sudo mkdir -p /data/configdb

# modify the config file to reflect...
# ...our new replica set config
sudo vi /etc/mongod.conf

Set the following values in your /etc/mongod.conf file:

# point to the directory we just created

# uncomment to use the default port
port = 27017

# name our replica set
replSet = primary

# allow the process to fork so you...
# ...can use your shell after spinning up
fork = true

# save and exit

Now, we're ready to start the replica node with the following command. Remember, you have to perform all of these steps on each virtual machine.

# start mongodb
mongod --config /etc/mongodb.conf

# ssh out to the host

Add Nodes to Our Replica Set

# ssh in
vagrant ssh primary

# enter the mongo shell

# start the replica set

# add current node
    "_id" : "primary"
    "version" : 1,
    "members" : [
            "_id" : 0,
            "host" "192,168.60.10:27017"

# add remaining nodes
{ "ok" : 1 }

{ "ok" : 1 }

No comments:

Post a Comment