3

I want to setup MongoDB replica set with docker-compose with only one node. This is my docker-compose.yml file:

version: '3.7'

services:
  mongodb1:
    image: mongo:latest
    command: mongod --replSet rs0
    ports:
      - 27017:27017
    volumes:
      - ./mongodb1/data:/data/db
    networks:
      - mongo-dev-net

  setup-rs:
    image: mongo:latest
    command: mongo mongodb://mongodb1:27017 --eval "rs.initiate();"
    depends_on:
      - mongodb1
    networks:
      - mongo-dev-net

networks:
  mongo-dev-net:
    driver: bridge

It gives me an error while trying to run command in setup-rs service. This is the error:

Error: couldn't connect to server mongodb1:27017, connection attempt failed: SocketException: Error connecting to mongodb1:27017 (MY_IP:27017) :: caused by :: Connection refused :

How should I initiate replica set without using any setup.sh file with only one node? Thanks in advance.

Eziz Durdyyev
  • 1,110
  • 2
  • 16
  • 34

1 Answers1

2

You need to first start your 2 mongodb instances and then call the initiate in a second moment (after both are started)

Something like:

#!/bin/bash

docker-compose up -d

sleep 5

docker exec mongodb1 /scripts/rs-init.sh

And in your mongodb1 you have the rs-init.sh script like:

#!/bin/bash

mongo <<EOF
var config = {
    "_id": "dbrs",
    "version": 1,
    "members": [
        {
            "_id": 1,
            "host": "mongodb1:27017",
            "priority": 1
        },
    ]
};
rs.initiate(config, { force: true });
rs.status();
EOF

You can take a look at the detailed step by step here

PS: I didn't test the full solution

Sergio Santiago
  • 1,316
  • 1
  • 11
  • 19
  • Might be worth clarifying that the second instance isn't an actual database, it's just using the same docker image to connect to the database running in the first instance to initialise it! – Matthew May 09 '22 at 12:37