2021年1月6日星期三

Why is my dockerized nodejs server not able to connect to my dockerized mongodb?

I have a mongodb docker container which is working correctly. I can query it from outside docker using localhost if I expose port 27017. I can query it from a python docker container on the same docker network using the mongo container name.

I also have a nodejs server in a docker container. It is on the same docker network as the mongodb container. If I create a simple test script and place it in the nodejs container, I am able to run it inside the nodejs container and successfully query the mongo container using the mongo containers name.

On a separate server, it I check out the project (identical code to where the problem is happening) and run "docker-compose up", the nodejs container is able to query the mongo container.

However, when running the project locally, the nodejs server code fails to connect to mongo using the container name. I constantly get the error "Connection to database failed, MongoNetworkError: failed to connect to server [sciencedog_db:27017] on first connect [MongoNetworkError: connection timed out]".

Can anyone give me any ideas regarding what to look for? The error seems clear enough, but a test script makes it clear that there is in fact connectivity between the containers. Is there any way that a node server could be configured that would make the connection to the mongo container fail when the network is working? Is there some environmental factor I am missing?

Test script which works when run directly with node:

const { MongoClient } = require("mongodb");    // Replace the uri string with your MongoDB deployment's connection string.  const uri =  //   "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority";      "mongodb://sciencedog_db:27017";    const client = new MongoClient(uri);    async function run() {    try {      await client.connect();        const database = client.db('sciencedog');      const collection = database.collection('users');        // // Query for a movie that has the title 'Back to the Future'      const query = { username: 'daniel' };      const user = await collection.findOne(query);        console.log(user);    } finally {      // Ensures that the client will close when you finish/error      await client.close();    }  }  run().catch(console.dir);  

Code in nodejs server which fails (part of a larger module), application is run with gulp:

const MongoClient = require('mongodb').MongoClient    const host = process.env.MODE === 'development' ? 'localhost' : 'sciencedog_db'  const dbUrl = `mongodb://${host}:27017`  const dbName = 'sciencedog'    var db_client  function getConnection() {      /**       * Get a connection to the database.       * @return {MongoClient} Connection to the database       */      return new Promise(function (resolve, reject) {          if (typeof db_client == 'undefined') {              console.log("There is no db_client");              MongoClient.connect(dbUrl).then(                  function (client) {                      console.log("So we got one");                      db_client = client                      console.log("Connected successfully to server");                      resolve(db_client)                  },                  function (err) {                      let err_msg = 'Connection to database failed, ' + err                      console.log(err_msg);                      reject(err_msg)                  }              )          } else {              console.log('Found existing database connection');              resolve(db_client)          }      })  }  

My docker-compose file:

version: '3.7'  services:      sciencedog_python:          build: .          container_name: sciencedog_python          init: true          stop_signal: SIGINT          environment:              - 'PYTHONUNBUFFERED=TRUE'          networks:              - sciencedog          ports:              - 8080:8080              - 8443:8443          volumes:              - type: bind                source: /etc/sciencedog/.env                target: /etc/sciencedog/.env                read_only: true              - type: bind                source: .                target: /opt/python_sciencedog/        sciencedog_node:          build: ../sciencedog/.          container_name: sciencedog_node          ports:              - 80:8001          networks:              - sciencedog          volumes:              - type: bind                source: /etc/sciencedog/.env                target: /etc/sciencedog/.env                read_only: true              - type: bind                source: ../sciencedog/src/.                target: /opt/sciencedog_node/src/        sciencedog_db:          image: mongo:4.0.4          container_name: sciencedog_db          volumes:              - sciencedog:/data/db          networks:              - sciencedog    volumes:      sciencedog:          driver: local    networks:      sciencedog:          driver: bridge  

docker-compose dev extension (enables connection from host, not needed for containers to communicate via docker network):

version: '3.7'  services:      sciencedog_python:          ports:              - 6900:6900          stdin_open: true          tty: true        sciencedog_db:          ports:              - 27017:27017  
https://stackoverflow.com/questions/65605396/why-is-my-dockerized-nodejs-server-not-able-to-connect-to-my-dockerized-mongodb January 07, 2021 at 09:17AM

没有评论:

发表评论