MongoDB Master-Slave cluster with authentication setup
Master Server
-
create mongo db folder with sub folders like data, conf, && log
mkdir-p/opt/mongo/datamkdir-p/opt/mongo/confmkdir-p/opt/mongo/log -
create a keyfile to secure mongo DB custer traffic. scp this file to slave server
cd/srv/mongodb/openssl rand -base64 741 >>mongo-keychmod700 mongo-key -
vi /opt/mongo/conf/master.conf
dbpath=/opt/mongo/datalogpath=/opt/mongo/log/mongodb.loglogappend=truefork=trueport=27017oplogSize=2048 - start mongo with command mongod --config /opt/mongo/conf/master.conf
-
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"}]} -
modify the conf file and add the last 3 lines into the file
dbpath=/opt/mongo/datalogpath=/opt/mongo/log/mongodb.loglogappend=truefork=trueport=27017oplogSize=2048master=trueauth=truekeyFile=/opt/mongo/mongo-key -
restart mongo with new config file
mongod --config/opt/mongo/conf/master.conf --shutdownmongod --config/opt/mongo/conf/master.conf
Slave Server
- create mongo db folder with sub folders like data, conf, && log; same as master
-
copy the keyfile to mongo folder and modify the slave.conf
dbpath=/opt/mongo/datalogpath=/opt/mongo/log/mongodb.loglogappend=truefork=trueport=27017oplogSize=2048slave=trueauth=truekeyFile=/opt/mongo/mongo-keysource= [master ip]:[port] -
start slave server
mongod --config/opt/mongo/conf/slave.conf -
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 testswitched to db test> db.products.insert( { item: "card", qty: 15 } )WriteResult({ "nInserted" : 1 })> show collectionsproducts |
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 testswitched to db test> db.dropDatabase(){ "dropped" : "test", "ok" : 1 }
|

浙公网安备 33010602011771号