How to deploy MongoDB Replica Set on Docker using Docker-Compose and Bash Script

Kenan Abbak
3 min readFeb 22, 2021

In this tutorial, I will try to explain how to set automated MongoDB replica set on docker. I tried a lot of things and this was the best fit version for me. This can be used as a starter and you can configure this for your needs.

What is it and why we need MongoDB replica set?

MongoDB replica set basically a group of mongod processes that maintain the same data set. We have 1 primary and 2 secondary(replicas) database servers. When the primary server down one of the replica servers will take the primary state. If you want to learn more about that you can read mongodb’s official doc about replication.

Prerequisites

$ docker pull mongo

1 - Define 3 Mongo nodes

At first, we should define our 3 mongo nodes.

Commands:

  • “ — replSet”, “-rs0”: Set all nodes with the same replica set named rs0.
  • “ — dbpath”, “/data/db”: Set database path to recover data.

Volumes:

We are creating 3 data file(data1, data2, data3). If the container deleted we can recover our data using these files.

Networks:

We should add 3 nodes to the database network because they should communicate and our config script must reach 3 of them.

2 - Create mongo setup bash script

Now we need to create our bash script which will initiate our replica set.

beginning we are sleep 15 I did this because I want to be sure all mongo nodes started.

mongodb1=$(getent hosts mongo1 | awk '{ print $1 }')
mongodb2=$(getent hosts mongo2 | awk '{ print $1 }')
mongodb3=$(getent hosts mongo3 | awk '{ print $1 }')

We are using “getent” and “awk” to resolve the IP addresses of our mongo nodes. Set our config, give “_id” and “priority”to every node because one of the nodes must take the PRIMARY, in this way that node with a high priority will take the primary state. And we set “{chainingAllowed: true}” with this setting, the SECONDARY member replicates from another SECONDARY member instead of from the PRIMARY. Finally, we are printing the status of our databases with“rs.status()”command

3 - Define mongo-config

Finally, we must define our mongo-config container and database network. The mongo-config container will run our bash script to initiate our replica set.

4 - Run and Test

To run docker container:

docker-compose up -d

rs.status() must return:

You can also check the status of databases:

docker exec -it mongo1 sh -c "mongo"
docker exec -it mongo2 sh -c "mongo"
docker exec -it mongo3 sh -c "mongo"

Finally

This is the solution that I found. I needed this because of elastic search. I see some tutorials but I want to show my solution too. I hope it helps someone. If you have a better solution I will be glad, if you inform me.

--

--