Last active
March 3, 2022 21:11
-
-
Save AlaeddineMessadi/f98da31f1cefa0cf920f8026bcf73fdb to your computer and use it in GitHub Desktop.
MongoDB Replication Set with Configuration file and scripts in docker-compose
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
version: "3" | |
services: | |
mongo1: | |
hostname: mongo1 | |
container_name: mongo1 | |
image: mongo:5.0.6 | |
expose: | |
- 27017 | |
ports: | |
- 27011:27017 | |
restart: always | |
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ] | |
networks: | |
- replset-network | |
volumes: | |
- ./data/db1:/data/db | |
- ./init.sh:/scripts/init.sh | |
mongo2: | |
hostname: mongo2 | |
container_name: mongo2 | |
image: mongo:5.0.6 | |
expose: | |
- 27017 | |
ports: | |
- 27012:27017 | |
restart: always | |
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ] | |
networks: | |
- replset-network | |
volumes: | |
- ./data/db2:/data/db | |
mongo3: | |
hostname: mongo3 | |
container_name: mongo3 | |
image: mongo:5.0.6 | |
expose: | |
- 27017 | |
ports: | |
- 27013:27017 | |
restart: always | |
networks: | |
- replset-network | |
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ] | |
volumes: | |
- ./data/db3:/data/db | |
networks: | |
replset-network: | |
driver: bridge |
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
#!/bin/bash | |
mongo <<EOF | |
var config = { | |
"_id": "rs0", | |
"version": 1, | |
"members": [ | |
{ | |
"_id": 1, | |
"host": "mongo1:27011", | |
"priority": 1 | |
}, | |
{ | |
"_id": 2, | |
"host": "mongo2:27012", | |
"priority": 2 | |
}, | |
{ | |
"_id": 3, | |
"host": "mongo3:27013", | |
"priority": 3 | |
} | |
] | |
}; | |
rs.initiate(config, { force: true }); | |
rs.status(); | |
EOF |
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
#!/bin/bash | |
docker-compose --file docker-compose.yml up -d | |
sleep 7 | |
docker exec mongo1 /scripts/init.sh |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As there will be an election to choose which member will be PRIMARY, mongo1 has the highest chance to be the Primary server.
therefore you have to check first with one is the PRIMARY then use it in the database connection string
localhost:27011 is the host:port of mongo1