Docker setting for mongodb replica set
Clone or download
Latest commit abc9777 Nov 3, 2018
Type Name Latest commit message Commit time
Failed to load latest commit information.
dev fix word Nov 1, 2018
images write down document Oct 21, 2018
.gitignore fix git ignore Nov 1, 2018
LICENSE Initial commit Oct 20, 2018 Update Nov 2, 2018

MongoDB replica set

Simple MongoDB replica set docker compose file.

In order to use Transaction function in MongoDB, you need a set of a replicated databases named MongoDB replica set.

This project makes it easy to build a MongoDB replica set circumstances by using docker container.


This project uses a Docker container for virtualizing Database circumstances. Therefore, Docker must be installed

To set localhost host environment, Direnv must be installed

how to install direnv?

install with brew

brew install direnv

set bash configuration(if you use bash) set zsh configuration(if you use zsh)

vi ~/.bashrc or vi ~/.zshrc

# add below configuration
eval "$(direnv hook bash)" or eval "$(direnv hook zsh)"

# apply
source ~/.bashrc or source ~/.zshrc


Pull all the necessary docker image from docker hub and set up replica set configuration

docker-compose up

Set host name so that localhost can connect to docker container's internal ip with given mongodb configuration setting

direnv allow

Set host for connecting to docker inner network

Changing directory to /dev triggers direnv setting so that hostname mongo-rs0-1, mongo-rs0-2, mongo-rs0-3 will be registered in you pc

cd dev

If you have Err: direnv: error .envrc is blocked Run direnv allow to approve its content.

direnv allow

Check which server is Primary node

docker exec mongodb-replica-set_mongo-rs0-1_1 bash -c 'mongo --eval "rs.status()"'

result Result

In members field you can find member who has "PRIMARY" in "stateStr" field, and that is a Primary Node

Connect to replica set

mongo 'mongodb://test:test1234@mongo-rs0-1:27017,mongo-rs0-2:27018,mongo-rs0-3:27019/test?replicaSet=rs0'

Connect to primary node

mongo --host `mongo mongo-rs0-1:27017 --quiet --eval "db.isMaster()['primary']"`

Create Account

Create Admin Account

use admin
db.createUser({user: "root", pwd: "test1234", roles: [{ role: "root", db: "admin" }] });

Create Database and matching account

use testdb
 { user: "test",
 pwd: "test1234",
 roles: ['readWrite','userAdmin'] } )