how to check if mongodb is up and ready to accept connections from bash script?

后端 未结 6 1420
眼角桃花
眼角桃花 2020-12-28 20:33

I have a bash shell script which does a bunch of stuff before trying to mongorestore.

I want to make sure that not only MongoDB is up, but it is also re

6条回答
  •  伪装坚强ぢ
    2020-12-28 21:05

    I needed Mongo running in Docker to initialize before creating a user. I combined the answers of Tom and Björn. This is the script I am using:

    #!/bin/bash
    
    # Wait until Mongo is ready to accept connections, exit if this does not happen within 30 seconds
    COUNTER=0
    until mongo --host ${MONGO_HOST} --eval "printjson(db.serverStatus())"
    do
      sleep 1
      COUNTER=$((COUNTER+1))
      if [[ ${COUNTER} -eq 30 ]]; then
        echo "MongoDB did not initialize within 30 seconds, exiting"
        exit 2
      fi
      echo "Waiting for MongoDB to initialize... ${COUNTER}/30"
    done
    
    # Connect to the MongoDB and execute the create users script
    mongo ${FWRD_API_DB} /root/create-user.js --host ${MONGO_HOST} -u ${MONGO_ROOT_USER} -p ${MONGO_ROOT_PASSWORD} --authenticationDatabase admin
    

提交回复
热议问题