Preparations
The following needs to be run only once
1 | mkdir -p ~/docker-storage/{rc1,rc2,rc3,mongo-keys} |
Reusable scripts
1 | start_cluster() { |
Put the above functions into your .bashrc
or .zshrc
or just a plain script file, i.e. util.sh
and source it:
1 | source util.sh |
Bring up the cluster and enter rc1
1 | start_cluster |
Once in mongo shell,
1 | use admin |
You will be back to the bash shell of rc1
, type the following to get back to first replica with the newly created credential.
1 | mongo -u superuser -p supercool --authenticationDatabase admin |
When mongo shell appears again, issue the following
1 | config = { |
You should see
{ "ok" : 1 }
test-set:SECONDARY>
Run rs.status()
a few times you should be able to see rc1 becomes the MASTER node.
Now it’s time to create a regular user:
1 | use admin |
Log in to rc1 mongo shell again with appUser
1 | mongo -u appUser -p appPass --authenticationDatabase admin |
Once in mongo shell of rc1
1 | use app |
Verify replication
To verify replication is working, enter rc2
, login to mongo shell with the appUser
credentials above, and run
1 | use app |
The output would look something like the following:
test-set:SECONDARY> db.list.find()
{ "_id" : ObjectId("5c0f2181080076162e179f22"), "title" : "one" }
{ "_id" : ObjectId("5c0f2181080076162e179f23"), "title" : "two" }
Test with a real node.js project
If you are not satisfied, you can go on and create a simple node.js project to test the replica set:
1 | docker pull node |
and enter (or just copy/paste) the following code
1 | const MongoClient = require('mongodb').MongoClient |
Save it, and run it with
1 | runnode cluster-auth-test.js "--net=mongo-cluster" |
Result:
start
[ { _id: 5c0f2181080076162e179f22, title: 'one' },
{ _id: 5c0f2181080076162e179f23, title: 'two' } ]
end
Note: Since I am running node version 8 in my system, I put node:8
in the runnode
script, you might need to adjust that to a different version if version 8 is not installed on your system.