Search code examples
mongodbdockerphp-7

ConnectionTimeoutException: No suitable servers found while inserting data into mongodb database


I am new in Docker and Mongodb. I have following in my docker-compose.yml file.

version: '3.3'
services:
    web:
      build:
        context: ./
        dockerfile: Dockerfile
      container_name: php73
      volumes:
        - ./src:/var/www/html/
      ports:
        - 8000:80
      depends_on:
        - db
      networks:
        - my-network
    db:
      image: mongo:latest
      container_name: mymongo
      restart: always
      ports:
        - '27017-27019:27017-27019'
      networks:
        - my-network
networks:
  my-network:

Following file is run in php container. it just creates a database and insert some collectins into the database.

<?php
require 'vendor/autoload.php';

$myClient = new MongoDB\Client('mongodb://127.0.0.1:27017');

$mydb = $myClient->my_db;
$mycollection = $mydb->my_collection;

$insertData = $mycollection->insertOne([
                'doc1' => 'abc', 
                'doc2' => 'def'
                ]);
?>

But, it shows following error:

PHP Fatal error:  Uncaught MongoDB\\Driver\\Exception\\ConnectionTimeoutException: No suitable servers found (`serverSelectionTryOnce` set): [connection refused calling ismaster on '127.0.0.1:27017'] in /var/www/html/vendor/mongodb/mongodb/src/functions.php:431\nStack trace:\n#0 /var/www/html/vendor/mongodb/mongodb/src/functions.php(431): MongoDB\\Driver\\Manager->selectServer(Object(MongoDB\\Driver\\ReadPreference))\n#1 /var/www/html/vendor/mongodb/mongodb/src/Collection.php(929): MongoDB\\select_server(Object(MongoDB\\Driver\\Manager), Array)\n#2 /var/www/html/mycode.php(16): MongoDB\\Collection->insertOne(Array)\n#3 {main}\n  thrown in /var/www/html/vendor/mongodb/mongodb/src/functions.php on line 431, referer: http://localhost:8000/index.php

I could not figure out why it is showing ConnectionTimeoutException. Could anyone give any hints ?


Solution

  • Update your connection string to

    <?php
    require 'vendor/autoload.php';
    
    $myClient = new MongoDB\Client('mongodb://db:27017');
    // or new MongoDB\Client('mongodb://db:27017');
    $mydb = $myClient->my_db;
    $mycollection = $mydb->my_collection;
    
    $insertData = $mycollection->insertOne([
                    'firstname' => 'abc', 
                    'lastname' => 'def'
                    ]);
    ?>
    

    docker-compose create network by default, you can access other container using container name, where 127.0.0.1 refer to localhost of the php container, not DB container.