Node / Express app can't connect to docker mon

2019-02-10 12:00发布

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?

1条回答
女痞
2楼-- · 2019-02-10 12:36

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.

查看更多
登录 后发表回答