Joe
Joe

Reputation: 4234

Connection nodejs and mongo with docker

This is my docker-compose-file:

version: "2"
services:
  rest-api:
    build: .
    ports:
      - "3007:3007"
    links:
      - mongo
  mongo:
    image: mongo
    volumes:
      - /data/mongodb/db:/data/db
    ports:
      - "27017:27017"

This is my Dockerfile:

FROM mhart/alpine-node:latest

RUN rm -rf /tmp/node_modules
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/

WORKDIR /opt/app
ADD . /opt/app

EXPOSE 3007

CMD ["node", "index.js"]

When I run the image, node is not able to connect to mongo:

MongoError: failed to connect to server [localhost:27017] on first connect

What can be wrong? How can I debug this?

Update:

In my node app I have:

let connection = mongoose.connect('mongodb://localhost/myapp');

Upvotes: 2

Views: 2902

Answers (2)

Peter Grainger
Peter Grainger

Reputation: 5107

In your node app you need to reference your container instead of localhost.

In your connection string to mongo use the name mongo as the host you are probably just using the default at the minute

https://docs.mongodb.com/manual/reference/connection-string/

e.g.

mongodb://mongo:27017/

You need to do this because the mongo database is in a separate container (with a different IP address) they are linked via TCP so localhost relates to the container node is in.

Upvotes: 2

jdno
jdno

Reputation: 4364

Node is trying to connect to Mongo on localhost, which fails because it is not running in the same container as Node. Instead, it runs in a different container, i.e. on a different host.

You probably have a line like this in your application:

var url = 'mongodb://localhost:27017/myproject';

It defines where the MongoDB is located. You need to change localhost to the actual host, which in your case would be mongo.

Upvotes: 6

Related Questions