Question

PHP connection to MongoDB cluster

Posted July 2, 2021 130 views
MongoDBPHP

Hello, I’ve difficulties with connection to MongoDB cluster on DigitalOcean by PHP. As we know, we have to use SSL, but I don’t know how. My code is as follows:

<?php
require_once __DIR__ . "/vendor/autoload.php";
$db = new MongoDB\Client('mongodb://[myapp].mongo.ondigitalocean.com', array(
    'username' => 'doadmin',
    'password' => '[password]',
    'db'       => '[database]',
    'authSource' => 'admin',
    'replicaSet' => '[replica]',
    'tls' => 'true',
    'tlsCAFile' => '/usr/share/ca-certificates/app/ca-certificate.pem'
));

$db = $conn->[database];
$collection = $db->[collection];
?>

I am getting an error: ‘Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found’.

Do you know how to connect properly in this case? Thank you in advance.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Hi there @MichalGiza,

I have just tested this with the code snippet that you’ve provided and it all worked as expected.

As you are getting a connection timeout exception, this is most likely caused by one of the following:

  • Port 27017 is closed for outgoing connections on your server, if this is the case you need to make sure that it is open.

  • You have used the Trusted sources functionality and locked down your database cluster for a specific IP only. If this is the case you would need to allow your server IP as well so that it could connect to the database cluster.

You could test the connectivity after that with the mongo command-line tool to make sure that you actually can connect to the cluster:

mongo "mongodb+srv://doadmin:password@cluster_name.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=replica_set_name" --tls --tlsCAFile <replace-with-path-to-CA-cert>

Let me know how it goes!
Regards,
Bobby

  • Hi! Thank you for your answer. I don’t use firewall like UFW as well as ‘Your cluster is open to all incoming connections’. Droplet is located at NYC1 and MongoDB at NYC3. Could this be the reason?

    Full PHP error: Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve '[app]-ad319710.mongo.ondigitalocean.com'] in /var/www/html/vendor/mongodb/mongodb/src/functions.php:431 Stack trace: #0 /var/www/html/vendor/mongodb/mongodb/src/functions.php(431): MongoDB\Driver\Manager->selectServer() #1 /var/www/html/vendor/mongodb/mongodb/src/Collection.php(651): MongoDB\select_server() #2 /var/www/html/index-inc.php(3): MongoDB\Collection->find() #3 /var/www/html/index.php(28): include('/var/www/html/i...') #4 {main} thrown in /var/www/html/vendor/mongodb/mongodb/src/functions.php on line 431

    • Hi there,

      I think that this should not be the case, I’ve tested this with a Droplet in Frankfurt and a MongoDB in NYC.

      Do you also get the same error when running the mongo command via your terminal?

      Also, when did you create the cluster?

      Regards,
      Bobby

      • I can connect via terminal without any problems. MongoDB database and Droplet were created on July 2

        • Hi there @MichalGiza,

          As you are able to connect via the terminal, this indicates that there are no network problems between the Droplet and the Database Cluster which is a good thing.

          What is the PHP version that you are using? I’ve tested this with PHP 8.

          Regards,
          Bobby

          • Wow, so this works for you? I’m aware that my above code doesn’t return errors in error.log. But if you need to do an operation on MongoDB, it doesn’t work

            I use PHP7.4

          • Hi there @MichalGiza,

            Try updating your connection string from:

            $db = new MongoDB\Client('mongodb://[myapp].mongo.ondigitalocean.com', array(
            

            To:

            $db = new MongoDB\Client('mongodb+srv://[myapp].mongo.ondigitalocean.com', array(
            

            Let me know how this goes!
            Regards,
            Bobby

          • @bobbyiliev So I created new MongoDB instance, downloaded new certificate and still the same :)

            Edit: Now CRT is good (according to error): DNSHostNotFound: Failed to look up service “mongodb.tcp.[app]-8cf9649f.mongo.ondigitalocean.com”: Success

          • Hi there @MichalGiza,

            The DNS lookup error should be fixed after adding +srv to the connection string. Let me know how it goes.

            Regards,
            Bobby

          • @bobbyiliev I rebuilt my Droplet and set up new MongoDB cluster. Similar error: {"t":{"$date":"2021-07-06T17:29:52.900Z"},"s":"E", "c":"NETWORK", "id":23256, "ctx":"ReplicaSetMonitor-TaskExecutor","msg":"SSL peer certificate validation failed","attr":{"error":"SSL peer certificate validation failed: self signed certificate in certificate chain"}}

            Connection string:

            mongo "mongodb+srv://doadmin:[password]@db-mongodb-fra1-89686-64b9afba.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=db-mongodb-fra1-89686&tls=true&tlsCAFile=ca-certificate.crt"