Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

mongodb

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 ready to accept connections before i try restore.

Right now, what I am seeing is, mongo process is up but it take 45+ seconds to do the initial setup (setting up journal files etc) before it is ready to accept connections. Ideally I want to keep testing the connection in a loop and only when I am able to connect, I want to run mongorestore.

Can someone show me how to do this in Bash or point me in the right direction?

like image 701
Silent User Avatar asked Mar 15 '13 22:03

Silent User


People also ask

How does shell script connect to MongoDB?

To open up the MongoDB shell, run the mongo command from your server prompt. By default, the mongo command opens a shell connected to a locally-installed MongoDB instance running on port 27017 . Try running the mongo command with no additional parameters: mongo.

How do I make sure MongoDB is installed?

To ensure that you have MongoDB installed correctly, run mongo --version and mongod --version . If you get an error for either, you'll need to go back and reinstall the database server. To start the server, run mongod --noauth --dbpath ~/mongo/data/db .


Video Answer


2 Answers

To test the connection in a loop like you suggest,

until nc -z localhost 27017
do
    sleep 1
done
like image 191
that other guy Avatar answered Oct 10 '22 06:10

that other guy


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.

like image 40
Björn Avatar answered Oct 10 '22 06:10

Björn