×


Unable to connect to MongoDB in Docker container - How to fix this error

Some of our customers was unable to connect to MongoDB in a docker container.

He received the below error message:

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

You have to tell the container to use it's own IP Address instead of localhost.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to related errors while troubleshooting Docker issues.


How to fix the error "Unable to connect to MongoDB in docker container" ?

Recently, one of our customers approached us saying that he was 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, he got the below 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

Here we found that the customer was confused with the internal port with the public port. 

So, we suggested our customer to use the below command:

$mongo IP:49155

This resolved the error.


We also, provide the below steps to customers if they are on Mac and using Docker Machine:

1. First, get the name of the VM running docker daemon.

For that, run the below command.

$ docker-machine ls

2. Next, get the VM’s IP info. For that, run the below command.

$ docker-machine env

3. Finally, connect with the mongo client to the VM IP and the mongo mapped port. For that, run the below command.

$ mongo VM-IP:port


[Need urgent assistance in fixing Docker errors? – We are here to help you. ]


Conclusion

This article covers solution to the error "Unable to connect to MongoDB in docker container".

Basically, this Docker error happens when there is a port issue.

if a container listens on 127.0.0.1, then the host can't map ports to it.

You need to listen on 0.0.0.0 or similar, and then the -p can reach the container's interface.


How do Docker ports work?

The -P command opens every port the container exposes. 

Docker identifies every port the Dockerfile exposes and the ones that are exposed with the Docker container build --expose parameter. 

Every exposed port is bound directly on a “random” port of the host machine.

The docker build command builds Docker images from a Dockerfile and a “context”. A build's context is the set of files located in the specified PATH or URL . 

The build process can refer to any of the files in the context. 

For example, your build can use a COPY instruction to reference a file in the context.