Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node / Express app can't connect to docker mongodb

Tags:

docker

mongodb

I want to run a node app that uses express and connects to a (boot2docker) docker mongo container.

When I first wrote the app, I was using a locally installed instance of mongodb, and the following config worked:

module.exports = {
  env: 'development',
  mongo: {
    uri: 'mongodb://localhost/fullstack-dev'
  }
};

And it ran as expected.

Now I'm trying to swap that out for a docker instance of mongo.

So, I've done the following steps to get mongo running:

$ docker pull mongo:latest
$ docker run -v "$(pwd)":/data --name mongo -d mongo mongod --smallfiles
$ docker ps

#my mongo instance is 442c2541fe1a
$ docker exec -it 442c2541fe1a bash
$ mongo

At this point, appears to be running in my command prompt.

Then, I tried to get the IP of boot2docker vm that runs docker on osx:

$ boot2docker ip
# the IP returned: 192.168.59.103

So, then, I went to swap out the old mongodb path in the nodejs config to the following:

module.exports = {
  env: 'development',
  mongo: {
    uri: 'mongodb://192.168.59.103:27017/fullstack-dev'
  }
};

and when I run the application, I get a connection error.

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: failed to connect to [192.168.59.103:27017]

What is the proper config for connecting my MEAN stack application with a docker'ified mongodb instance?

like image 627
Kristian Avatar asked May 02 '15 06:05

Kristian


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?

MongoDB can be run in a Docker container. There is an official image available on Docker Hub containing the MongoDB community edition, used in development environments. For production, you may custom-build a container with MongoDB's enterprise version.


1 Answers

You need to publish the appropriate port on the container with the -p argument i.e:

docker run -p 27017:27017 -v "$(pwd)":/data --name mongo -d mongo mongod --smallfiles

The will make port 27017 accessible on the host (the VM in your case) and forward traffic to port 27017 on the container.

like image 157
Adrian Mouat Avatar answered Oct 13 '22 00:10

Adrian Mouat