I have problems to connect a nodeJS application which is running as a docker container to a mongoDB. Let me explain what I have done so far:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3a3732cc1d90 mongo:3.4 "docker-entrypoint..." 3 weeks ago Up 3 weeks 27017/tcp mongo_live
As you can see, there is already a mongo docker container running.
Now I'm running my nodeJS application docker container (which is a build from meteorJS):
$ docker run -it 0b422defbd59 /bin/bash
In this docker container I want to run the application by running:
$ node main.js
Now I'm getting the error
Error: MONGO_URL must be set in environment
I already tried to set MONGO_URL by setting:
ENV MONGO_URL mongodb://mongo_live:27017/
But this doesn't work:
MongoError: failed to connect to server [mongo_live:27017] on first connect
So my question is how to connect to a DB, which is - as far as I understand - 'outside' of the running container. Alternativly how do I set up a new DB to this container?
There are couple of ways to do it.
run your app in the same network as your mongodb:
Also you can link two containers:
use mongodb container ip address:
You can bind your mongodb port to your host and use host's hostname in your app
You can use
docker network
and run both apps in the same networkYou could pass
--add-host mongo_live:<ip of mongo container>
to docker run for your application and then usemongo_live
for mongodb urlYou can also use docker compose to make your life easier ;)
...
Please use below snippet for your docker-compose.yml file, replace comments with your actuals. Should solve your problem.
Please use the below links for references :
1) NodeJs Docker
2) MongoDb docker
3) docker-compose tutorial
Best of Luck
When you run containers each container works in independent network. Because one container cant connect to other point to point.
The are 3 ways to connect containers
127.0.0.1 mongo_live
(This is the simplest way)Add mongodb to application container is not docker way.