MongoDB

Secure MongoDB Replica Setup

ssh to server1 edit /etc/hosts to contain other two servers server2, server3
repeat action for all servers respectively

Server Setup

ssh to server

cd &&
openssl rand -base64 756 > keyfile &&
chmod 400 keyfile

scp keyfile [email protected]:~/
scp keyfile [email protected]:~/

sudo chown mongodb:mongodb keyfile
sudo mv keyfile /var/lib/mongodb/

edit /etc/mongod.conf

Replace #security with:

#security:
  #keyFile: /var/lib/mongodb/keyfile

Replace #replication with:

replication:
  replSetName: rs0              (or whatever name you want)

Save edits and exit

sudo systemctl restart mongod.service

ssh to server2,server3 and repeat the Server Setup section

Initiate Connection

ssh to server1

mongo
> rs.initiate()
> rs.add('server2:27017')
> rs.add('server3:27017')

Now one of the servers should be the PRIMARY and others should be SECONDARY

On the same server, edit /etc/mongod.conf

Replace:

#security:
  #keyFile: /var/lib/mongodb/keyfile

with:

security:
  keyFile: /var/lib/mongodb/keyfile

Save edits and exit

sudo systemctl restart mongod.service

ssh to server2, server3 and repeat the Initiate Connection section

again one of the servers should be the PRIMARY and others should be SECONDARY

ssh to the PRIMARY server

mongo
> use admin
> db.createUser({user: "yourUsernameHere", pwd: "yourPasswordHere", roles: [{role: "userAdminAnyDatabase", db: "admin"}, {role: "clusterAdmin", db: "admin"}]})
> use myDB
> db.createUser({user: "databaseUsernameHere", pwd: "databasePasswordHere", roles: [{role: "readWrite", db: "myDB"}]})

ssh to SECONDARY

mongo
> rs.slaveOk()

ssh to other SECONDARY

mongo
> rs.slaveOk()

to verify everything was done correctly

ssh to PRIMARY

mongo
> use admin
> db.auth("yourUsernameHere", "yourPasswordHere")
1
> use myDB
> db.auth("databaseUsernameHere", "databasePasswordHere")
1
> for (var i = 0; i<= 10; i++) db.replicaTestCollection.insert( { x : i } )
WriteResult({ "nInserted" : 1 })
> exit

ssh to any SECONDARY

> use myDB
> db.auth("databaseUsernameHere", "databasePasswordHere")
1
> db.replicaTestCollection.count()
11

Credit to bergerg for this guide.

Comments