Skip to content

Instantly share code, notes, and snippets.

@oleurud
Last active November 16, 2023 16:57
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 30 You must be signed in to fork a gist
  • Save oleurud/d9629ef197d8dab682f9035f4bb29065 to your computer and use it in GitHub Desktop.
Save oleurud/d9629ef197d8dab682f9035f4bb29065 to your computer and use it in GitHub Desktop.
[Local mongo replicaset with docker] #docker #mongo
# pull the official mongo docker container
docker pull mongo
# create network
docker network create my-mongo-cluster
# create mongos
docker run -d --net my-mongo-cluster -p 27017:27017 --name mongo1 mongo mongod --replSet my-mongo-set --port 27017
docker run -d --net my-mongo-cluster -p 27018:27018 --name mongo2 mongo mongod --replSet my-mongo-set --port 27018
docker run -d --net my-mongo-cluster -p 27019:27019 --name mongo3 mongo mongod --replSet my-mongo-set --port 27019
# add hosts
127.0.0.1 mongo1 mongo2 mongo3
# setup replica set
docker exec -it mongo1 mongo
db = (new Mongo('localhost:27017')).getDB('test')
config={"_id":"my-mongo-set","members":[{"_id":0,"host":"mongo1:27017"},{"_id":1,"host":"mongo2:27018"},{"_id":2,"host":"mongo3:27019"}]}
rs.initiate(config)
# connection URI
mongodb://localhost:27017,localhost:27018,localhost:27019/{db}?replicaSet=my-mongo-set
@crapthings
Copy link

how to write a docker-compose file?

@harveyconnor
Copy link

@gsantosgonzalez
Copy link

Excelent, thanks a lot. I didn't add mongos to the hosts file.

@SuddenGunter
Copy link

worked on local linux machine, but for robo3t connection I used mongo1, mongo2 and mongo3 names.
didn't work when try connect using localhost:...

@harveyconnor
Copy link

@SuddenGunter You'll need to add 127.0.0.1 mongo1 mongo2 mongo3 to your hosts file

@Tariqs
Copy link

Tariqs commented Mar 2, 2021

This replicaSet is created on a single machine. Can you please point to a resource where the writer has used 3 different machines?

@MahdadGhasemian
Copy link

Excelent.

@ddo88
Copy link

ddo88 commented Aug 27, 2021

I love you bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment