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

To test the connection in a loop like you suggest,

until nc -z localhost 27017
do
    sleep 1
done

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.


A solution using MongoDB Tools. Useful in a docker container or something similiar where you do not want to install nc.

until mongo --eval "print(\"waited for connection\")"
  do
    sleep 60
  done

Based on that other guy's answer.

Tags:

Bash

Mongodb