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

I have a bash script that fails. After checking, it turns out that the failure is caused by the fact that MongoDB is accessed immediately after a restart.

For example, launch:

mongo --eval "db.version()"

gives the expected result:

MongoDB shell version: 2.4.9
connection to: test
2.4.9

during operation:

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

outputs the following result: my contribution:

mongodb stop / waiting
mongodb start / running, process 1466
MongoDB shell version: 2.4.9
connection to: test
Sat Oct 25 02: 52: 29.736 Error : Could not connect to server 127.0.0.1:27017 in src / mongo / shell / mongo.js: 145
exception: connection failed

because the server is not ready yet.

bash script , MongoDB ?

  • service mongodb status , , .

  • nc -z localhost 27017 , 0, , , ( - ?)

+4
3

mongo db:

mongo --nodb

:

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);

2 , Script.js, :

mongo --nodb Script.js

EDIT: , , , . .

+7

@Magnitus, - .

var conn;
var interval = 100;   // 100 Milliseconds polling
var timeout  = 10000; // 10 Seconds timeout
var startTime = new Date();
connectionUrl = connectionUrl.split('/')[2];

if (connectionUrl.indexOf('@') !== -1) {
  // Has auth (doesn't need auth for test connection)
  connectionUrl = connectionUrl.split('@')[1];
}

while(conn === undefined) {
  try {
    var elapsed = (new Date() - startTime);
    print("Attempting to connect to " + connectionUrl + " elapsed: " + elapsed + "ms");
    conn = new Mongo(connectionUrl);
  } catch(error) {
    print(error);

    if ((new Date() - startTime) >= timeout) {
      print("ERROR: Failed to establish connection within timeout (" + timeout + "ms)");
      quit(1);
    } else {
      sleep(interval);
    }
  }
}

print("MongoDB connection established in " + (new Date() - startTime) + "ms");

:

export MONGO_URL="mongo://<user>:<pass>@<host>:<port>/<database>"
mongo --nodb wait_for_mongo.js --eval "connectionUrl=\"$MONGO_URL\""

script host: , MONGO_URL="mongo://localhost" .

+3

Instead of fixing this in a script, the best option (at least for my script) is to fix it in the mongo init script / upstart unit / systemd service.

For systemd:

ExecStartPost=/bin/sh -c 'while ! /usr/bin/mongo --eval "db.version()" > /dev/null 2>&1; do sleep 0.1; done'

+3
source

All Articles