MongoNetworkError when connecting from different container

372 views
Skip to first unread message

John Cogan

unread,
Oct 23, 2019, 8:50:59 PM10/23/19
to mongodb-user
PHP dev new to NodeJS and I am struggling to get my NodeJS container to connect to my MongoDB container. As far I can see I have all the correct NPMs installed in my Docker file and the docker-compose is correct. Please note that I have not added the containers to the same network or but in the link to the db service into the nodejs container, although I did try this and got pretty much the same result.

Unsure why I am getting the error below when I bash into the nodejs container and run `node app.js`

Error

    
[nodemon] clean exit - waiting for changes before restart
   [nodemon] restarting due to changes...
   [nodemon] starting `node app.js`
   (node:92) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
   Server is listening on port 3000
   Could not connect to the database. Exiting now... { MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED localhost:27017]
       at Pool.<anonymous> (/usr/src/app/node_modules/mongodb/lib/core/topologies/server.js:431:11)
       at Pool.emit (events.js:193:13)
       at createConnection (/usr/src/app/node_modules/mongodb/lib/core/connection/pool.js:559:14)
       at connect (/usr/src/app/node_modules/mongodb/lib/core/connection/pool.js:973:11)
       at makeConnection (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:39:11)
       at callback (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:261:5)
       at Socket.err (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:286:7)
       at Object.onceWrapper (events.js:281:20)
       at Socket.emit (events.js:193:13)
       at emitErrorNT (internal/streams/destroy.js:91:8)
       at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
       at processTicksAndRejections (internal/process/task_queues.js:81:17)
     name: 'MongoNetworkError',
     errorLabels: [ 'TransientTransactionError' ],
     [Symbol(mongoErrorContextSymbol)]: {} }


docker-compose.yml

   
 version: '3.5' # We use version 3.5 syntax
   services: # Here we define our service(s)
     frontend:
       container_name: angular
       build: ./angular_app
       volumes:
         - ./angular_app:/usr/src/app
       ports:
         - 4200:4200
       command: >
         bash -c "npm install && ng serve --host 0.0.0.0 --port 4200"
       depends_on:
         - api
   
     # NodeJS/Express service for API
     api:
       image: nodeexpress
       build:
         context: ./node_server
         dockerfile: Dockerfile
       volumes:
         - ./node_server:/usr/src/app
         - /usr/src/app/node_modules
       ports:
         - 3000:3000
       links:
         - mongoservice
       depends_on:
         - mongoservice
   
     # Mongo database service
     mongoservice:
       image: mongo
       container_name: mongocontainer
       restart: always
       environment:
         MONGO_INITDB_ROOT_USERNAME: ${DB_MONGO_ROOTUSER}
         MONGO_INITDB_ROOT_PASSWORD: ${DB_MONGO_ROOTPWD}
       ports:
         - ${DB_MONGO_EXTERNAL_PORT}:${DB_MONGO_INTERNAL_PORT}
       volumes:
         - ${DB_MONGO_VOLUME1}
   
     mongo-express:
       image: mongo-express
       restart: always
       ports:
         - 8081:8081
       environment:
         ME_CONFIG_MONGODB_ADMINUSERNAME: root2
         ME_CONFIG_MONGODB_ADMINPASSWORD: secret2
   
   volumes:
       data:
         external: true
   
   networks:
     default:
       driver: bridge


Dockerfile (for api service - nodejs express)

    
FROM node:11-alpine
   
   RUN mkdir -p /usr/src/app
   
   WORKDIR /usr/src/app
   
   COPY . .
   
   RUN npm install
   #RUN npm install mysql
   RUN npm install mongodb --save
   #RUN npm install --save body-parser express mysql2 sequelize helmet cors
   RUN npm install --save body-parser express mongoose helmet cors
   RUN npm install --save nocache
   RUN npm install nodemon --save
   
   EXPOSE 4300
   
   #CMD ["npm", "run", "start"]
   CMD [ "npm", "run", "start.dev" ]


app.js

    
const express = require('express');
   const bodyParser = require('body-parser');
   
   // create express app
   const app = express();
   
   // parse requests of content-type - application/x-www-form-urlencoded
   app.use(bodyParser.urlencoded({ extended: true }))
   
   // parse requests of content-type - application/json
   app.use(bodyParser.json());
   
   // Configuring the database
   const dbConfig = require('./config/database.config');
   const mongoose = require('mongoose');
   
   mongoose.Promise = global.Promise;
   
   // Connecting to the database
   // Connection string variants attempted
   // mongodb://root:secret@mongoservice:27017/angapp2
   mongoose.connect('mongodb://root:secret@localhost:27017/angapp2', {
     useNewUrlParser: true
   }).then(() => {
     console.log("Successfully connected to the database");
   }).catch(err => {
     console.log('Could not connect to the database. Exiting now...', err);
     process.exit();
   });
   
   // define a simple route
   app.get('/', (req, res) => {
     res.json({"message": "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
   });
   
   // Require Notes routes
   require('./routes/note.routes.js')(app);
   
   // listen for requests
   app.listen(3000, () => {
     console.log("Server is listening on port 3000");
   });


What I've tried:

1. Attempted the various connection string variants in terms of the host name, i.e. localhost, 127.0.0.1, 0.0.0.0, mongoservice

2. Also ran `docker inspect <container-id>` on the mongo service and got the internal IP address of the container and tried that in the connection string

3. Added `RUN npm install mongodb --save` to node servers Dockerfile

4. Managed to connect Robo 3D GUI to the Mongo container without issue

5. Bashed into Mongo service and managed to log into the DB and run some statements as a test that the service was working fine.

Kevin Adistambha

unread,
Nov 1, 2019, 12:00:27 AM11/1/19
to mongodb-user

Hi,

I tried a simplified variation of your docker-compose.yml file:

version: '3.5'
services:
  mongoservice:
    image: mongo
    container_name: mongocontainer
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - 27017:27017
  nodeservice:
    image: nodecontainer
    build:
      context: .
      dockerfile: Dockerfile
    container_name: nodecontainer
    links:
      - mongoservice
    depends_on:
      - mongoservice
    ports:
      - 3000:3000
networks:
  default:
    driver: bridge

Using the connection string of:

mongodb://root:root@mongoservice:27017

allowed the node container to connect to the mongo container in my case, as expected. localhost or 127.0.0.1 won’t work since the MongoDB server was not running locally in the node container. It needs to be mongoservice.

If you’re still having issues connecting to the mongo container, you might want to remove the other services and concentrate on getting the api connect to mongoservice first.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages