MongoDB Master-Slave cluster with authentication setup


Master Server

  1. create mongo db folder with sub folders like data, conf, && log

    mkdir -p /opt/mongo/data mkdir -p /opt/mongo/conf mkdir -p /opt/mongo/log
  2. create a keyfile to secure mongo DB custer traffic. scp this file to slave server

    cd /srv/mongodb/ openssl rand -base64 741 >>mongo-key chmod 700 mongo-key
  3. vi /opt/mongo/conf/master.conf

    dbpath=/opt/mongo/data logpath=/opt/mongo/log/mongodb.log logappend=true fork=true port=27017 oplogSize=2048
  4. start mongo with command mongod --config /opt/mongo/conf/master.conf
  5. login mongo and create admin account && local account repl for the cluster

    > use admin > db.createUser({user:"root", pwd:"123456", roles:[{role:"root", db:"admin"}]}) > db.createUser({user:"repl", pwd:"123456", roles:[{role:"dbOwner", db:"local"}]}) > show users {     "_id" : "admin.root",     "user" : "root",     "db" : "admin",     "roles" : [         {             "role" : "root",             "db" : "admin"         }     ] } {     "_id" : "admin.repl",     "user" : "repl",     "db" : "admin",     "roles" : [         {             "role" : "dbOwner",             "db" : "local"         }     ] }
  6. modify the conf file and add the last 3 lines into the file

    dbpath=/opt/mongo/data logpath=/opt/mongo/log/mongodb.log logappend=true fork=true port=27017 oplogSize=2048     master=true auth=true keyFile=/opt/mongo/mongo-key
  7. restart mongo with new config file

    mongod --config /opt/mongo/conf/master.conf --shutdown mongod --config /opt/mongo/conf/master.conf

Slave Server

  1. create mongo db folder with sub folders like data, conf, && log; same as master
  2. copy the keyfile to mongo folder and modify the slave.conf

    dbpath=/opt/mongo/data logpath=/opt/mongo/log/mongodb.log logappend=true fork=true port=27017 oplogSize=2048     slave=true auth=true keyFile=/opt/mongo/mongo-key source = [master ip]:[port]
  3. start slave server

    mongod --config /opt/mongo/conf/slave.conf
  4. login slave with admin credential, and active slave (important)

    rs.slaveOk()

Test

Create a test db and insert values into a new collection on master node

> use test switched to db test > db.products.insert( { item: "card", qty: 15 } ) WriteResult({ "nInserted" : 1 }) > show collections products

Login to slave node and then verfiy if the new added test db exisits.

After the verification done, remember to delete the test db with command 

> use test switched to db test > db.dropDatabase() "dropped" "test""ok" : 1 }