6

What I have

I try to connect my nodejs app to a mongoDB-Container. I did this with Mediums-Tutorial open, so my dockerfiles look like this:

Dockerfile

FROM node:carbon
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install 
COPY . . 

EXPOSE 8085
CMD ["npm","start"]

docker-compose.yml

version: "2"
services: 
  metis:
    build: .
    ports:
      - "8085:8085"
    links:
      - mongo

  mongo:
      image: mongo
      volumes:
        - /data/mongodb/db:/data/db
      ports:
        - "27017:27017"

But when I try to connect to the database, I recieve

name    "MongoNetworkError"
message "failed to connect to server [localhost:27017] on first connect         [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]"

With my app looking like this:

let mongodb = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017'
const dbName = 'metis'

mongodb.connect(url, (err, client) => {
        if (err) reject(err)
        else {
            const db = client.db(dbName)

            db.collection(type + ":" + entity).insertOne(document, (error, result) => {
                if (error) reject(error)
                else { resolve(result) }
            })

            client.close()
        }
    })
})

It works normally when I simply start the node app and mongodb-server by themselves. ut when composing in Docker, I just cannot get a connection. I do not have any clue why. If you have any questions, please feel free to ask.

Building the docker-image with docker itself also works, but with no connection to any outside mongodb.

My question is:

How should I connect MongoDB-Container and my App in Docker?

1 Answer 1

17

Instead of using localhost use the service name given to the mongo service mongo

const url = 'mongodb://mongo:27017'

Also check if you really need to expose the mongo port on the host.

Sign up to request clarification or add additional context in comments.

2 Comments

For reference: "By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name." (docs.docker.com/compose/networking)
Thanks, this was indeed the issue!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.