2

I would like to run MongoDB in a container, this works:

docker run -p 27017:27017 --name cdt -d mongo

then I want to run a server in another container, like so:

docker run --name foo --link cdt:mongo exec /bin/bash -c "node server.js"

The node.js server attempts to make a mongodb connection to localhost:27017, but it fails to make the connection.

Anyone know why that might happen? Am I not linking the containers correctly?

Note that I can successfully connect to the mongodb container from outside a container, but not from the server inside the "foo" container.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

7

So localhost from a container is always (99.5% of the time) referring to the container itself. This is also 99.5% of the time not what you want. If you're using links like this, you need to change localhost:27017 to mongo:27017 as that's what you're 'mounting' the link as (--link cdt:mongo).

A better option is to use Docker networks instead of links (which are deprecated). So:

$ docker network create my-net
$ docker run --name cdt --net my-net -d mongo
$ docker run --name foo --net my-net exec /bin/bash -c "node server.js"

Now you'd refer to your db via cdt:27017 as the names of the containers become resolvable via DNS on the same network. Note that you don't need to expose a port if you're not intending to connect from the outside world, inter-connectivity between containers on the same network doesn't require port mapping.

johnharris85
  • 17,264
  • 5
  • 48
  • 52