1024programmer Java How to connect nodeJSdocker container to mongoDB

How to connect nodeJSdocker container to mongoDB

I have a problem connecting a nodeJS application running as a docker container to 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 (this is the meteorJS build):

$ docker run -it 0b422defbd59 /bin/bash
 

Inside this docker container, I want to run the following command to run the application:

$ node main.js
 

Now I’m getting an error

Error: MONGO_URL must be set in environment
 

I have tried setting MONGO_URL via settings:

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 the database, which as far as I understand – is “outside” the running container. Also, how do I set up a new database for this container?

1> Boynux..:


There are several ways to do this.

Run your application on the same network as mongodb:

docker run --net container:mongo_live your_app_docker_image

 # then you can use mongodb in your localhost
 $ENV MONGO_URL mongodb://localhost:27017/
 

You can also link two containers:

docker run --link mongo_live:mongo_live you_app_image ..
 # Now mongodb is accessible via mongo_live
 

Use mongodb container ip address:

docker inspect -f '{{.NetworkSettings.IPAddress}}' mongo_live
 # you will get your container ip here

 $ docker run -it 0b422defbd59 /bin/bash
 # ENV MONGO_URL mongodb://[ip from previous command]:27017/
 

You can bind the mongodb port to the host and use the host’s hostname in your application

You can docker network use and run both applications on the same network

You can --add-host mongo_live: pass docker run to your application and then use mongo_livemongodb url

You can also use docker compose to make your life easier 😉

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/765002

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索