Reputation: 93
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?
Upvotes: 6
Views: 4651
Reputation: 3001
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.
Upvotes: 17