Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to wait until MongoDB is ready after restart?

I have a bash script which fails. After inspection, it appears that the failure is due to the fact that MongoDB is accessed immediately after being restarted.

For example, running:

mongo --eval "db.version()"

gives the expected output:

MongoDB shell version: 2.4.9
connecting to: test
2.4.9

while running:

service mongodb restart; mongo --eval "db.version()"

produces the following output, emphasis mine:

mongodb stop/waiting
mongodb start/running, process 1466
MongoDB shell version: 2.4.9
connecting to: test
Sat Oct 25 02:52:29.736 Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145
exception: connect failed

because the server is not ready yet.

What is the correct way to wait during the execution of the bash script until MongoDB is actually ready?

  • service mongodb status is not a solution, because it reports the status of the service, and not the database itself.

  • Doing nc -z localhost 27017 repeatedly until its exit code becomes 0 will work, but I'm not sure if there are no drawbacks (running somehow an infinite loop?)

like image 691
Arseni Mourzenko Avatar asked Oct 25 '14 02:10

Arseni Mourzenko


People also ask

How do I stop MongoDB from restarting?

One liners to start or stop mongodb service using command line; To start the service use: NET START MONGODB. To stop the service use: NET STOP MONGODB.


1 Answers

To start the mongo interpreter without connection to any db:

mongo --nodb

From there, inside the mongo interpreter you can execute:

var conn;
try
{
    conn = new Mongo("localhost:27017");
}
catch(Error)
{
    //print(Error);
}
while(conn===undefined)
{
    try
    {
        conn = new Mongo("localhost:27017");
    }
    catch(Error)
    {
        //print(Error);
    }
    sleep(100);
}
DB = conn.getDB("test");
Result = DB.runCommand('buildInfo');
print(Result.version);

With the 2 above, you can put the later part in a file like Script.js and then do:

mongo --nodb Script.js

EDIT: There, totally forgot that what you really wanted was the version. Fixed that for you.

like image 57
Magnitus Avatar answered Oct 05 '22 13:10

Magnitus