I would like to start this MongoDB Replica Set:
version: "3"
services:
  mongo1:
    image: mongo
    ports:
      - 27017:27017
    command: mongod --replSet rs0
  mongo2:
    image: mongo
    ports:
      - 27018:27017
    command: mongod --replSet rs0
  mongo3:
    image: mongo
    ports:
      - 27019:27017
    command: mongod --replSet rs0
Wait for those to come up, then access the Mongo shell via terminal:
docker exec -it mongo1 mongo
Then in Mongo shell do:
rs.initiate({"_id":"rs0","members":[{"_id":0,"host":"mongo1:27017"},{"_id":1,"host":"mongo2:27017"},{"_id":2,"host":"mongo3:27017"}]})
Mongo also allows mongo --eval "rs.initiate(..)", which may make things easier.
My question is how do I run this command after mongo1, mongo2, mongo3 are up?
You can do this, I recently had to run mongo --repair then run the MongoDB itself and after the MongoDB is up I needed to add my user to the DB, you can easily change things to run commands only after all three MongoDBs are up.
Possible docker-compose.yml:
version: "2"
services:
  mongo:
    container_name: mongo
    restart: on-failure:10
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=<user>
      - MONGO_INITDB_ROOT_PASSWORD=<pass>
      - MONGO_INITDB_DATABASE=db
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
    command: bash -c "mongod --repair && mongod"
  mongoClient:
    image: mongo
    container_name: mongoClient
    links:
      - mongo
    volumes:
      - ./deployment_scripts:/deployment_scripts
    command: 
      - /deployment_scripts/add_user.sh
    depends_on:
      - mongo
  app:
    container_name: app
    restart: always
    build: .
    volumes:
      - .:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - mongoClient
    links:
      - mongo
My /deployment_scripts/add_user.sh script wait for MongoDB to be up:
until mongo --host mongo --eval "print(\"waited for connection\")"
do
    sleep 1
done
// you can add more MongoDB waits here
echo "Adding user to MongoDB..."
mongo --host mongo --eval "db.createUser({ user: \"<user>\", pwd: \"<pass>\", roles: [ { role: \"root\", db: \"admin\" } ] });"
echo "User added."
Note that you can address all three of your MongoDBs by replacing --host mongo with your --host mongo1 --host mongo2 and --host mongo3. You'll use this for both of the eval commands in the script.
Credit to this SO answer https://stackoverflow.com/a/45060399/4295037 that I used (until mongo ...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With