'Problem while rs.initiate() for setup docker-compose for replica set

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergio Santiago