Last active
August 2, 2022 14:14
-
-
Save ranfysvalle02/da9e7ca970211c2e6a3db9f25c9bb7b5 to your computer and use it in GitHub Desktop.
MongoDB Replicaset with Docker w/ Compass Connectivity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
---First, make sure Docker networking is set up--- | |
docker network create my-mongo-cluster | |
docker network ls | |
---Now, run the containers --- | |
docker run -d -p 3001:3001 --name mongo1 --net my-mongo-cluster mongo mongod --replSet my-mongo-rs --port 3001 | |
docker run -d -p 3002:3002 --name mongo2 --net my-mongo-cluster mongo mongod --replSet my-mongo-rs --port 3002 | |
docker run -d -p 3003:3003 --name mongo3 --net my-mongo-cluster mongo mongod --replSet my-mongo-rs --port 3003 | |
---Then, login to mongo1 --- | |
docker exec -it mongo1 mongo --port 3001 | |
---FROM mongo1--- | |
config = { "_id" : "my-mongo-rs", "members" : [ { "_id" : 0, "host" : "mongo1:3001" }, { "_id" : 1, "host" : "mongo2:3002" }, { "_id" : 2, "host" : "mongo3:3003" } ] } | |
rs.initiate(config) | |
---Make edits to /etc/hosts/ for Compass to be able to connect to the replicaset--- | |
127.0.0.1 mongo1 | |
127.0.0.1 mongo2 | |
127.0.0.1 mongo3 | |
---Flush DNS cache to make sure the /etc/hosts stuff is reflected--- | |
sudo dscacheutil -flushcache | |
---Please wait enough time for the replicaSet to be initiated--- | |
---If you run into this error:--- | |
---"Error: couldn’t add user: not master" (https://stackoverflow.com/questions/31387053/cant-create-user)--- | |
---Simply restart the mongo shell--- | |
use admin | |
db.createUser( { user: "mongoadmin", pwd: "mongoadmin123", roles:["root"] }) | |
---MongoDB Compass Connection String--- | |
mongodb://mongoadmin:mongoadmin123@localhost:3001/?replicaSet=my-mongo-rs&authMechanism=DEFAULT | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OPTIONAL
---CONFIRM WRITES ARE REPLICATED TO NODE---
rs.secondaryOk()
docker exec -it mongo2 mongo --port 3002
use [test_db]
db.[test_collection].find()