Use Docker to run MongoDB Replica Set


Step 1: Pull Mongo DB images

docker pull mongo:4

root@tutorialspots1:~# docker pull mongo:4
4: Pulling from library/mongo
e0b25ef51634: Pull complete
c7a086fc80ea: Pull complete
7a6592c2fb05: Pull complete
5dad2281c276: Pull complete
34073132290c: Pull complete
fd66acd9aeb7: Pull complete
f8c57c4e1a23: Pull complete
9744d80c4b59: Pull complete
fc817eca8f95: Pull complete
d81c93cf7d21: Pull complete
Digest: sha256:25c874a0ef870085269317aec259f0aa619c272804bc990a83fb17174cdfd2b2
Status: Downloaded newer image for mongo:4
docker.io/library/mongo:4

Step 2: Create a docker network
Example network name: mongo-replicaset
docker network create mongo-replicaset

Step 3: Run mongo containers:
docker run -d --net mongo-replicaset -p 27017:27017 --name mongoset1 mongo:4 mongod --replSet mongodb-replicaset --port 27017

Step 4: UFW

sudo ufw allow from 5.111.0.0/16 to any port 27017

read more: How To Set Up a Firewall with UFW on Ubuntu 20.04

Step 5: add to /etc/hosts file:

5.111.22.33 mongoset1
5.111.22.44 mongoset2
5.111.22.55 mongoset3

Step 6:
With other servers, repeat steps 1-5

Step 7: Configure ReplicaSet

docker exec -it mongoset1 mongo

Paste content:

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

Sample output:

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

MongoDB connection string to use

mongodb://<hostname1>:27017,<hostname2>:27017,<hostname3>:27017/<Your database name>?replicaSet=mongodb-replicaset

Step 8: fix security problem
How to fix docker and ufw security problem

1 Comment

Leave a Reply