Reputation: 415
I am trying to create local setup of mongo with 3 repilca nodes
I have create docker compose file which contains 3 mongo nodes.
but when i am unable to connect to mongo with compass, its throwing ENOTFOUND errror.
mongo connection string -
mongodb://localhost:27017/
mongodb://mongo1:27017/
mongodb://:27017/
version: '3'
services:
mongo1:
image: mongo:4.4
container_name: mongo1
ports:
- "27017:27017"
networks:
- elk-net
volumes:
- ./data/mongo1:/data/db
command: mongod --replSet rs0 --bind_ip_all
mongo2:
image: mongo:4.4
container_name: mongo2
ports:
- "27018:27017"
networks:
- elk-net
volumes:
- ./data/mongo2:/data/db
command: mongod --replSet rs0 --bind_ip_all
mongo3:
image: mongo:4.4
container_name: mongo3
ports:
- "27019:27017"
networks:
- elk-net
volumes:
- ./data/mongo3:/data/db
command: mongod --replSet rs0 --bind_ip_all
networks:
elk-net:
Upvotes: 1
Views: 465
Reputation: 5339
You can find below a working solution for MongoDB replica set (It contains 2 replicas). The docker-compose.yml has several useful comments.
docker-compose.yml:
version: "3.8"
services:
mongo1:
image: mongo:4.4.5
hostname: mongo1
networks:
- mongo_net
# The following variables won't be used due to set entrypoint section
# The replica-set sets automatically, but the admin user has to be set
# only one time when you use new deploy.
# I guess it can be automated, but I didn't have time for it...
# Eg.:
# docker exec -it <docker-container-id> mongo
# use admin
# db.createUser({ user: "admin", pwd: "admin_pwd", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })
environment:
- MONGO_INITDB_DATABASE=test_db
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin_pwd
- MONGO_DATA_DIR=/data/db
volumes:
- mongo-1:/data/db
- ./docker-entrypoint-mongo.sh:/data/docker-entrypoint.sh
# Probably the expose is not needed because the services can
# communicate via any port inside Docker Network.
expose:
- 27017
entrypoint:
- bash
- -c
- |
chmod +x /data/docker-entrypoint.sh
exec /data/docker-entrypoint.sh
healthcheck:
test: test $$(echo "rs.initiate({_id:'my-replica-set',members:[{_id:0,host:\"mongo1:27017\"},{_id:1,host:\"mongo2:27017\"}]}).ok || rs.status().ok" | mongo --quiet ) -eq 1
interval: 10s
start_period: 30s
mongo2:
image: mongo:4.4.5
hostname: mongo2
networks:
- mongo_net
environment:
- MONGO_INITDB_DATABASE=test_db
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin_pwd
- MONGO_DATA_DIR=/data/db
volumes:
- mongo-2:/data/db
- ./docker-entrypoint-mongo.sh:/data/docker-entrypoint.sh
expose:
- 27017
entrypoint:
- bash
- -c
- |
chmod +x /data/docker-entrypoint.sh
exec /data/docker-entrypoint.sh
volumes:
mongo-1:
mongo-2:
networks:
mongo_net: {}
docker-entrypoint-mongo.sh:
mongod "--enableMajorityReadConcern" "false" "--journal" "--dbpath" "/data/db" "--replSet" "my-replica-set" "--bind_ip_all"
The connection string for MongoDB replica-set:
mongodb://mongo1:27017,mongo2:27017/?replicaSet=my-replica-set
Upvotes: 0