Categories

[MongoDB] Replication in MongoDB

You are here:
< All Topics

ENVIRONMENT:

  • Ubuntu 16.02 LTS
  • MongoDB 4.2

Introduction to replication

Replication is a way of keeping identical copies of your data on multiple servers and is recommended for all production deployments. It keeps your application running and safe. With MongoDB you can set up replication by creating a Replica Set. It’s a group of servers that keep copies of the primary’s data. If the primary crashes, the secondaries can elect a new primary. If you are using replication and server goes down, you can still access your data from the other servers; if the data is damaged or inaccessible, you can make a new copy of the data from one of the other members.

Setting Up

I’m going to explain how to set up a 3-node replica set in a single machine so you can start experiment. In a production environment you should always use a replica set and allocate resources to each member to avoid resource contention and provide isolation against servers failure.

MONGO DB Replica Set

#Create file config filename mongod-repl-1.conf:
storage:
  dbPath: /var/mongodb/db/1
net:
  bindIp: 192.168.103.100,localhost
  port: 27001
security:
  authorization: enabled
  keyFile: /var/mongodb/pki/m103-keyfile
systemLog:
  destination: file
  path: /var/mongodb/db/mongod1.log
  logAppend: true
processManagement:
  fork: true
replication:
  replSetName: m103-repl


#Create the keyFile
sudo mkdir -p /var/mongodb/pki/
sudo chown vagrant:vagrant /var/mongodb/pki/
openssl rand -base64 741 > /var/mongodb/pki/m103-keyfile
chmod 400 /var/mongodb/pki/m103-keyfile


#Create dbpath for node1
mkdir -p /var/mongodb/db/node1


#Start mongod with node1
mongod -f node1.conf
cp node1.conf node2.conf
cp node2.conf node3.conf


#Change the mongod config


#Create directory
mkdir /var/mongodb/db/{node2,node3}


#Start mongod processes with node2.conf and node3.conf:
mongod -f node2.conf
mongod -f node3.conf


#Connect node1
mongo --port 27001


#Initiate replica Set
rs.initiate()


#Create dropUser
use admin
db.createUser({
  user: "m103-admin",
  pwd: "m103-pass",
  roles: [
    {role: "root", db: "admin"}
  ]
})

exit

mongo --host "m103-example/192.168.103.100:27001" -u "m103-admin" -p "m103-pass" --authenticationDatabase "admin"

rs.status()


#Add other members to replica Set
rs.add("m103:27002")
rs.add("m103:27003")

rs.isMaster()


#Step down the current primary
rs.stepDown()


#Check replica set
rs.isMaster()
Table of Contents