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

后端 未结 6 1556
眼角桃花
眼角桃花 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:10

    I recently had the same problem. I decided to configure mongod to log all it's output to a logfile and then wait in a loop checking the logfile until we see some output that suggests mongod is ready.

    This is an example logfile output line we need to wait for:

    Tue Dec  3 14:25:28.217 [initandlisten] waiting for connections on port 27017
    

    This is the bash script I came up with:

    #!/bin/bash
    
    # Initialize a mongo data folder and logfile
    mkdir -p /data/db
    touch /var/log/mongodb.log
    
    # Start mongodb with logging
    # --logpath    Without this mongod will output all log information to the standard output.
    # --logappend  Ensure mongod appends new entries to the end of the logfile. We create it first so that the below tail always finds something
    /usr/bin/mongod  --quiet --logpath /var/log/mongodb.log --logappend &
    
    # Wait until mongo logs that it's ready (or timeout after 60s)
    COUNTER=0
    grep -q 'waiting for connections on port' /var/log/mongodb.log
    while [[ $? -ne 0 && $COUNTER -lt 60 ]] ; do
        sleep 2
        let COUNTER+=2
        echo "Waiting for mongo to initialize... ($COUNTER seconds so far)"
        grep -q 'waiting for connections on port' /var/log/mongodb.log
    done
    
    # Now we know mongo is ready and can continue with other commands
    ...
    

    Notice the script will not wait forever, it will timeout after 60s - you may or may not want that depending on your use case.

提交回复
热议问题