Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect NodeJS-App to MongoDB using docker-compose

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?

like image 276
Coding Vampyre Avatar asked May 20 '18 15:05

Coding Vampyre


People also ask

How do I link a node JS project to MongoDB?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });

How do I connect to a MongoDB Docker container?

For connecting to your local MongoDB instance from a Container you must first allow to accept connections from the Docker bridge gateway. To do so, simply add the respective gateway IP in the MongoDB config file /etc/mongod. conf under bindIp in the network interface section.


1 Answers

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.

like image 191
Mohit Mutha Avatar answered Sep 27 '22 19:09

Mohit Mutha