Cannot connect to MongoDB via node.js in Docker

Viewed 16360

My node.js express app cannot connect to the MongoDB in a Docker. I'm not that familiar with Docker.

node.js connection:

import mongodb from 'mongodb';
...
mongodb.MongoClient.connect('mongodb://localhost:27017', ... );

Dockerfile:

FROM node:argon
RUN mkdir /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]

docker-compose.yml

version: “2”
 services:
  web:
   build: .
   volumes:
     — ./:/app
   ports:
   — “3000:3000”
   links:
    — mongo
   mongo:
    image: mongo
    ports:
      — “27017:27017”

Build command: docker build -t NAME .

Run command: docker run -ti -p 3000:3000 NAME

Connection error:

[MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]]
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]'
4 Answers

I am not sure if you still have this question, but the datasources.json should be:

"host": "mongo" 

rather than "localhost".

In my logs I see:

mongo    |  NETWORK  [listener] connection accepted from 172.22.0.3:47880 #1 (1 connection now open)

As you can see, docker compose will NAT mongo to another V-LAN. The IP address 172.22.0.0 is an internal IP address used by the daemon to route a docker-compose image. So localhost is now not in the game.

At least, it works for me.

datasources.json

"mongoDS": {
    "host": "mongo",
    "port": 27017,

...

in my case works like this :

just link to the container from the command line. db is my up database container

sudo docker run -it --link db:db1 --publish 4000-4006:4000-4006 --name backend backend:latest

Related