Mongodb "Remote Server Closed Connection" on first connection after reboot

After restarting the mongod service, I get a connection error for each database when I try to connect to PHP:

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

After reconnecting once, the connection works again. He does not mind if the connection is made immediately after a reboot 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 connection of the old mongo instance is used, but I cannot figure out how to fix this. Is there a way to get the Mongo driver to start a new connection when the first fails?

+5
source share
2 answers

Now we are using the solution that we restart Apache after rebooting MongoDB. Not the best solution, but it works :).

+18
source

There was the same problem. I can confirm that it is associated with the connection pool in the driver, and I did not find a valuable option. I can also confirm that this happens for the first new MongoClient () requests a few hours after restarting db.

I did to surround my new MongoClient () with try catch and repeat it. For instance. something like that:

 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 } 

Retry to max. 5 times is just paranoia. I have never experienced that more than one attempt has ever been required.

Hope this helps.

+4
source

Source: https://habr.com/ru/post/1200109/


All Articles