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

后端 未结 6 1552
眼角桃花
眼角桃花 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 20:54

    While Tom's answer will work quite well in most situations, it can fail if you are running your script with the -e flag. I mean you run your script with set -e at the very top. Why? Because Tom's answer relies on the exit status of the previous command, in this case grep -q which will fail if it does not find the required string, and therefore the entire script will fail. The -e flag documentation gives a clue on how to avoid this problem:

    The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !.

    So, one solution is to make the grep command part of the while condition. However, since he is running mongodb with the --logappend option the search string could appear as a result of a previous run. I combined that other guy answer with Tom's answer and it works really well:

    # Wait until mongo logs that it's ready (or timeout after 60s)
    COUNTER=0
    while !(nc -z localhost 27017) && [[ $COUNTER -lt 60 ]] ; do
        sleep 2
        let COUNTER+=2
        echo "Waiting for mongo to initialize... ($COUNTER seconds so far)"
    done
    

    I find that using tomcat is the best solution because it actually tests if there is something listening.

提交回复
热议问题