Home » Php » php – Mongodb "Remote server has closed the connection" on first connection after restart

php – Mongodb "Remote server has closed the connection" on first connection after restart

Posted by: admin July 12, 2020 Leave a comment

Questions:

After restart of the mongod service I get a connection error for every database when I try to connect with PHP:

Failed to connect to: localhost:27017: Remote server has closed the connection
500 Internal Server Error - MongoConnectionException

After one or two refeshes the connection works again. It doesn’t mind if the connection is made immediately after restart or after some time.

MongoDB version: 2.6.4
PHP MongoDB driver version: 1.5.5
Configuration: PHP-FPM with Apache2

I think the persistent connecting of the old mongo instance is used, but I can’t find out how to fix this. Is there any way to force the Mongo driver to start a new connection when the first one fails?

How to&Answers:

The solution we now use is that we restart Apache after we restart MongoDB. Not the best solution, but it works :).

Answer:

Had the same problem. I can confirm that it has to do with connection pooling in the driver and I didn’t find any valuable option. I can also confirm that this happens for the first new MongoClient() calls several hours after the db has been restarted.

What I did is to surround my new MongoClient( ) with a try catch and repeat it.
E.g. something like this:

try {
    $NoSQLDBMS_Connection = new MongoClient( $NoSQLDBMS_Host );
    $NoSQLDBMS_Database = $NoSQLDBMS_Connection->selectDB( $NoSQLDBMS_DBName );
} catch( Exception $e ) {
    // retry, mostly when mongodb has been restarted in order to get a new connection
    $MaxRetries = 5;
    for( $Counts = 1; $Counts <= $MaxRetries; $Counts ++ ) {
        try {
            $NoSQLDBMS_Connection = new MongoClient( $NoSQLDBMS_Host );
            $NoSQLDBMS_Database = $NoSQLDBMS_Connection->selectDB( $NoSQLDBMS_DBName );
        } catch( Exception $e ) {
            continue;
        }
        return;
    }
    // do something fancy here if mongodb is not reachable at all
}   

Retrying to max. 5 times is just paranoia. I never experienced that more than one retry was ever needed.

Hope it helps.