Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Mongo shell command after docker-compose?

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?

like image 878
atkayla Avatar asked Oct 27 '25 09:10

atkayla


1 Answers

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 ...).

like image 126
ofekp Avatar answered Oct 28 '25 23:10

ofekp