Cannot connect to MongoDB in docker on Windows host
I have a similar problem discussed in Cannot connect to MongoDB in docker.
- Windows host
- Docker Toolbox, so it is using VirtualBox
I used docker run --name mongo2 -p 127.0.0.1:27017:27017 mongo
to create the MongoDB container.
When I connect to the container (docker -it mongo2 /bin/bash
), I can connect to Mongo via mongo localhost:27017
.
I also checked with netstat that Mongo is listening on 0.0.0.0:27017, not only localhost.
Still, I'm not able to connect from my Windows host to the container. I even tried to disable Windows firewall and still nothing:
rs@ausus:~$ telnet localhost 27017
Trying 127.0.0.1...
telnet: Unable to connect to remote host: Connection refused
Any ideas?
Solution 1:
The answer is provided in the first comment actually (and it solved for me the same problem), but it is easier to find it when it is in the Answer section.
The answer will assume that you're using Docker Toolbox.
Instead of running:
docker run --name mongo2 -p 127.0.0.1:27017:27017 mongo
the following command should be run:
docker run --name mongo2 -p <ip of boot2docker VM>:27017:27017 mongo
To get the <ip of boot2docker VM>
VM:
- Go to VirtualBox --> select "default" VM --> click "Show" button.
- Run the command:
docker-machine env
. - The IP of the VM will be in the output.
Solution 2:
Like the Docker documentation says at https://hub.docker.com/_/mongo/ : "This means that it is not possible to run a MongoDB container with the data directory mapped to the host"
Finally I have done a .bat
script that defines my Win10 IP and map it to a variable.
I run MongoDB directly on my Win10 and then access it with the IP.
That is not what I want but it works.
startup.bat :
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set DOCKERHOST=%ip:~1%
docker-compose up
docker-compose.yml :
environment:
- MONGO_HOST=${DOCKERHOST}