Home Docker compose MongoDB single node replica set
Post
Cancel

Docker compose MongoDB single node replica set

Instructions

The steps to create a docker cluster are as follows.

  • Start one instance of MongoDB.
  • Initiate the Replica Set.

Once you have a MongoDB cluster up and running, you will be able to experiment with it.

How it will look like:

graph LR
    Application[Application] -- Read --> MongoDB(MongoDB)
    Application[Application] -- Write --> MongoDB(MongoDB)

Create docker compose file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
version: "3.9"
networks:
  mongodb-network:
    name: "mongodb-network"
    driver: bridge
services:
  mongodb:
    image: "mongo:6.0.4"
    container_name: "mongodb"
    networks:
      - mongodb-network
    hostname: "mongodb"
    ports:
      - "27017:27017"
    restart: "always"
    entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "myReplicaSet" ]
  mongoinit:
    image: "mongo:6.0.4"
    container_name: "mongodb_replSet_initializer"
    restart: "no"
    depends_on:
      - mongodb
    networks:
      - mongodb-network
    command: >
      mongosh --host mongodb:27017 --eval "rs.initiate({
       _id: \"myReplicaSet\",
       members: [
         {_id: 0, host: \"mongodb\"}
       ]
      })"

Launch it

1
docker compose up

Test and verify replica set

1
docker exec -it mongodb mongosh --eval "rs.status()"

References

This post is licensed under CC BY 4.0 by the author.