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
- I run ‘gen-mongo-key.sh’ which generates ‘mongo-keyfile’
- ‘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