node.jsmongodbdockerdocker-compose

MongoServerSelectionError: connect ECONNREFUSED when connecting Node.js app with MongoDB running on Docker


Docker-compose file looks like this

version: '3.8'
services:
  mongo:
    image: mongo
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: root
    ports:
      - "2617:2716"
  web:
    build: 
      context: .
    ports:
      - "8080:8080"
    environment:
      NODE_ENV: production
    depends_on:
      - mongo

.env file looks like this

BASE_URL=http://localhost:8080
MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD=root
DB_HOST=mongo
DB_PORT=2617
DB_NAME=ptcgp

And I connect through this string:

const mongoURI = 'mongodb://' + process.env.MONGO_INITDB_ROOT_USERNAME + ':' 
  + process.env.MONGO_INITDB_ROOT_PASSWORD + '@' 
  + process.env.DB_HOST + ':' 
  + process.env.DB_PORT + '/' 
  + process.env.DB_NAME + '?retryWrites=true&writeConcern=majority&authSource=admin';
mongoose.connect(mongoURI);

mongoURI looks like this: mongodb://root:root@mongo:2617/ptcgp?retryWrites=true&writeConcern=majority&authSource=admin which looks correct to me...

It returns the following error: MongoServerSelectionError: connect ECONNREFUSED 172.20.0.2:2617 and MongoDB connection error. Please make sure MongoDB is running. but the MongoDB container is running.

I am doing the same exact thing with another project running in Docker with the ports set as 2717:27017 (thus the choices of the ports in this deploy) and it is working.


Solution

  • Mongo listens on port 27017 by default.

    When containers talk to each other on the docker bridge network, they don't use the mapped ports. The mapped ports are for talking to containers from outside the bridge network. So if you only need to talk to a container from other containers, you don't need to map the port(s).

    Since each container has it's own IP address, containers can use the same port numbers without problem. But when you map them to host ports, you need to make sure that the mapped port numbers don't clash.

    So to map the Mongo port to host port 2617 you should do

    ports:
      - "2617:27017"
    

    But since port 2617 would only be used for accessing Mongo from outside the Docker network, you should use port 27017 from your webapp.