Setting up Mongo DB Cluster with Authentication

Hi, I am new to docker. I am able to run Mongo DB standalone. However, I am not able to setup a Mongo DB cluster with Authentication enabled. I am struggling for quite sometime and not able to setup. Please help.

The sequence of execution is

  1. I run ‘gen-mongo-key.sh’ which generates ‘mongo-keyfile’
  2. ‘docker compose up’ which executes docker-compose.yaml and loads init-mongo.sh

However, in step (2), I get the error ‘Unable to acquire security key[s]’. However, I can see the security file properly located in ‘/etc/mongo-keyfile’

gen-mongo-keyfile.sh

openssl rand -base64 756 > mongo-keyfile
chmod 400 mongo-keyfile

docker-compose.yaml

services:
  mongo1:
    image: mongo:7
    container_name: mongo1
    hostname: mongo1
    ports:
      - 27017:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=example
    volumes:
      - ./mongo-keyfile:/etc/mongo-keyfile
    command: ["mongod", "--replSet", "rs0", "--bind_ip", "localhost,mongo1", "--keyFile", "/etc/mongo-keyfile"]

  mongo2:
    image: mongo:7
    container_name: mongo2
    hostname: mongo2
    ports:
      - 27018:27017
    environment:
      - MONGO_INITDB_ROOT_USERNAME=root
      - MONGO_INITDB_ROOT_PASSWORD=example
    volumes:
      - ./mongo-keyfile:/etc/mongo-keyfile
    command: ["mongod", "--replSet", "rs0", "--bind_ip", "localhost,mongo2", "--keyFile", "/etc/mongo-keyfile"]

  setup:
    image: mongo:7
    depends_on:
      - mongo1
      - mongo2
    volumes:
      - ./init-mongo.sh:/scripts/init-mongo.sh
    entrypoint: ["bash", "-c", "sleep 10 && mongosh --host mongo1:27017 < /scripts/init-mongo.sh"]

init-mongo.sh

#!/bin/bash
echo ========== Initializing Mongo ==========
echo Waiting for 10 seconds
sleep 10

mongosh --host mongo1:27017 <<EOF
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "mongo1:27017" },
    { _id: 1, host: "mongo2:27017" }
  ]
})
EOF

mongosh --host mongo1:27017 <<EOF
use admin
db.createUser({
  user: "admin",
  pwd: "password",
  roles: [ { role: "root", db: "admin" } ]
})
EOF

Can you read the key file inside the container after chmod 400 mongo-keyfile?

Small note: For a cluster you usually need 3 instances, preferably on 3 nodes. And then depends_on doesn’t work anymore.

Thank you @bluepuma77 for your response.

  1. mongo-keyfile is correct. There’s no issue. And checked permissions too. It is fine.
  2. I can go with 3 nodes. Since I was getting errors, I thought to try with 2 nodes first so that it doesn’t produce too much of logs.
  3. If ‘depends-on’ doesn’t work, then what is the next step?