Skip to content

Instantly share code, notes, and snippets.

@oxycoder
Last active October 30, 2021 08:53
Show Gist options
  • Save oxycoder/a6148927d5fda224245fa16fe939536b to your computer and use it in GitHub Desktop.
Save oxycoder/a6148927d5fda224245fa16fe939536b to your computer and use it in GitHub Desktop.
MongoDB replicaset on Docker

Setup allow to connect mongo replicaset running inside docker from host machine.

Start

Production: docker compose up -d

Development: docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d

run init_replica.sh to setup mongodb replica after container start

Connect using Mongo Compass or Navicat

Addresses

  • mongodb_1:27017
  • mongodb_2:27017
  • mongodb_3:27017

ReplicaSet: -rs0

Connection String

mongodb://mongodb_1:27017,mongodb_2:27017,mongodb_3:27017?replicaSet=rs0

Restore database

docker exec -i mongodb_1 mongorestore --archive --gzip < ~/Downloads/backup.gz

version: '3.8'
services:
mongodb_1:
ports:
- 27001:27017
mongodb_2:
ports:
- 27002:27017
mongodb_3:
ports:
- 27003:27017
version: '3.8'
services:
mongodb_1:
restart: "no"
ports:
- 127.0.10.1:27017:27017
mongodb_2:
restart: "no"
ports:
- 127.0.10.2:27017:27017
mongodb_3:
restart: "no"
ports:
- 127.0.10.3:27017:27017
version: '3.8'
services:
mongodb_1:
container_name: mongodb_1
image: "mongo:latest"
networks:
- mongo_backend
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
restart: always
mongodb_2:
container_name: mongodb_2
image: "mongo:latest"
networks:
- mongo_backend
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
restart: always
mongodb_3:
container_name: mongodb_3
image: "mongo:latest"
networks:
- mongo_backend
entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
restart: always
networks:
mongo_backend:
# /etc/hosts
# For development
127.0.10.1 mongodb_1
127.0.10.2 mongodb_2
127.0.10.3 mongodb_3
#!/bin/bash
echo Checking replica status
status=$(docker exec -t mongodb_1 mongo --eval "rs.status().code" | tail -n1)
if [[ "$status" == *"94"* ]]; then
mongoAddr1=mongodb_1
mongoAddr2=mongodb_2
mongoAddr3=mongodb_3
replica="rs.initiate(
{
_id: 'rs0',
members: [
{ _id: 0, host: '$mongoAddr1:27017' },
{ _id: 1, host: '$mongoAddr2:27017' },
{ _id: 2, host: '$mongoAddr3:27017' },
]
}
)"
echo Creating replica with id: rs0
docker exec -t mongodb_1 mongo --eval "$replica"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment