26
votes

Following this example: https://docs.docker.com/engine/examples/mongodb/

When trying to connect to mongoDB with: mongo ip:27017 (where ip is the name from boot2docker ip) + the port number from docker ps:

27017/tcp
or with -P
0.0.0.0:49155->27017/tcp

Either way I get the following errors:

warning: Failed to connect to ip:27017, reason: errno:61 Connection refused

Error: couldn't connect to server ip:27017 (ip), connection attempt failed at src/mongo/shell/mongo.js:148 exception: connect failed

4
use docker logs <container> and ps to check that mongodb is actually running and listening on the port you exposed.ZeissS
ok checking the tutorial more in-depth: can you post the line from docker ps for the container? I think you confused the internal port with the public port.ZeissS
Thanks you made me think again :-)Chris G.
I hade the same and docker ps return: mongo_1 /entrypoint.sh --smallfile ... Up 0.0.0.0:27017->27017/tcpWael Ben Zid El Guebsi
Have you found a solution for this yet?user3335999

4 Answers

24
votes

If you specified the correct port and still not able to connect to mongodb running in docker (like me), make sure you are using the service name (or container name) in your connection URL, e.g. mongodb://mongodb_service:27017/mydb, which is defined in your docker-compose.yml :

services:
  mongodb_service:
    image: mongo

I was using the hostname value and that's not the correct thing to do. You could verify this by looking at docker inspect mongodb_service in the Aliases section.

15
votes

I was using port 27017 instead of 49155 (doh, port forwarding)

0.0.0.0:49155->27017/tcp

Thanks to ZeissS

12
votes

If you are on a Mac and using Docker Machine, do the following:

1. Get the name of the VM running docker daemon
$ docker-machine ls

2. Get the VM's IP info
$ docker-machine env 

3. Connect with the mongo client to the VM IP and the mongo mapped port
$ mongo VM-IP:port
1
votes
DATABASE_URI=mongodb://mongo:27017/db_name

Should be the Database URI for a service definition like below (and not mongodb://localhost or mongodb://IP). Use service name or container name.

services  
  mongo:
    container_name: mongo
    image: mongo
    ports: 
      - '27017:27017'