Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect nodeJS docker container to mongoDB

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?

like image 622
user3142695 Avatar asked May 14 '17 08:05

user3142695


People also ask

How do I connect to a MongoDB Docker container?

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.

Can I use MongoDB in Docker?

Can MongoDB Run in a Docker Container? MongoDB can run in a container. The official image available on Docker Hub contains the community edition of MongoDB and is maintained by the Docker team. This image can be used in a development environment.


1 Answers

There are couple of ways to do it.

  • run your app in the same network as your 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/
    
  • Also you can 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 you container ip here
    
    $ docker run -it 0b422defbd59 /bin/bash
    # ENV MONGO_URL mongodb://[ip from previous command]:27017/
    
  • 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 network

  • You could pass --add-host mongo_live:<ip of mongo container> to docker run for your application and then use mongo_live for mongodb url

  • You can also use docker compose to make your life easier ;)

...

like image 64
Boynux Avatar answered Sep 28 '22 05:09

Boynux