how to check if mongodb is up and ready to accept connections from bash script?
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 logfilemkdir -p /data/dbtouch /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=0grep -q 'waiting for connections on port' /var/log/mongodb.logwhile [[ $? -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.logdone# 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.