How to run MongoDB replica set on Docker

September 06, 2019

Introduction

This post is about hosting MongoDB replica set cluster with dockerised images.

Steps to create MongoDB replica-set

1. Pull Mongo DB images

I have tested this on Mongo image version 4.

docker pull mongo:4

2. Create a docker network

docker network create mongo-cluster-dev

Give any name of network you want. But, this will be referenced later. Keep its name.

3. Run mongo containers

docker run -d --net mongo-cluster-dev -p 27017:27017 --name mongoset1 mongo:4 mongod --replSet mongodb-replicaset --port 27017
docker run -d --net mongo-cluster-dev -p 27018:27018 --name mongoset2 mongo:4 mongod --replSet mongodb-replicaset --port 27018
docker run -d --net mongo-cluster-dev -p 27019:27019 --name mongoset3 mongo:4 mongod --replSet mongodb-replicaset --port 27019

We are just running three containers in same network we created above.

4. Need to add them in your /etc/hosts file

Open /etc/hosts
Append in the end of file:

127.0.0.1       mongoset1 mongoset2 mongoset3

4. Configure ReplicaSet

Need to login to one container, and run command.

docker exec -it mongoset1 mongo

It will open up mongo shell in first container. Copy following, and paste it to that shell.

db = (new Mongo('localhost:27017')).getDB('test')
config={"_id":"mongodb-replicaset","members":[{"_id":0,"host":"mongoset1:27017"},{"_id":1,"host":"mongoset2:27018"},{"_id":2,"host":"mongoset3:27019"}]}
rs.initiate(config)

This will give some output, something like this:

{
	"ok" : 1,
	"$clusterTime" : {
		"clusterTime" : Timestamp(1567674525, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	},
	"operationTime" : Timestamp(1567674525, 1)
}

Note the status: “ok” above.

MongoDB connection string to use

mongodb://<hostname>:27017,<hostname>:27018,<hostname>:27019/<Your database name>?replicaSet=mongodb-replicaset

Similar Posts

Latest Posts