Cannot connect to MongoDB via node.js in Docker
Try:
mongodb.MongoClient.connect('mongodb://mongo:27017', ... );
Change your docker-compose.yml
:
version: "2"
services:
web:
build: .
volumes:
- ./:/app
ports:
- "3000:3000"
links:
- mongo
mongo:
image: mongo
ports:
- "27017:27017"
And use some docker compose commands:
docker-compose down
docker-compose build
docker-compose up -d mongo
docker-compose up web
I am not sure if you still have this question, but the datasources.json
should be:
"host": "mongo"
rather than "localhost".
In my logs I see:
mongo | NETWORK [listener] connection accepted from 172.22.0.3:47880 #1 (1 connection now open)
As you can see, docker compose will NAT mongo to another V-LAN. The IP address 172.22.0.0
is an internal IP address used by the daemon to route a docker-compose
image. So localhost
is now not in the game.
At least, it works for me.
datasources.json
"mongoDS": {
"host": "mongo",
"port": 27017,
...
Try this.
- When using linked docker containers you should use the name of the container in this case for example your connection to mongodb should be
mongodb.MongoClient.connect('mongodb://mongo:27017', ... );
instead ofmongodb.MongoClient.connect('mongodb://localhost:27017', ... );
. The reason for changing it to mongo is because you used the links attribute to mongo in yourdocker-compose.yml
. That would result to a hostname of mongo in your/etc/hosts
of the web docker container. Reference linking-containers. The docker-compose.yml seems to be lacking an indention. On the mongo attribute should be the same level as web.
version: '2' services: web: build: . volumes: ['./:/app'] ports: [ '3000:3000' ] links: [ mongo ] mongo: image: mongo ports: [ '27017:27017' ]
I tried your configuration using my docker what Ive done is update
docker-compose.yml
then Idocker-compose build
thendocker-compose up
. Logs of my local run