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?
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 });
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With