Bram  Vanbilsen
Bram Vanbilsen

Reputation: 6505

Connecting to Mongo on host using `host.docker.internal`

I have a server running in a docker container which is trying to connect to a mongo database on the host system. To do so, I use the following connection string: mongodb://host.docker.internal:27017/db_name.
This works fine on my Mac, but when running it on Ubuntu, it stops working for me. My initial thought was that host.docker.internal did not get resolved properly. But it does! I verified this using a server on the host to which I was able to connect from the container. Also, the error message does mention the resolved ip:

connect ECONNREFUSED 172.17.0.1:27017

I run my container as follows:

sudo docker run --env-file ./.env --add-host=host.docker.internal:host-gateway image:latest

My guess is that I need to allow connections coming from 172.17.0.1 in my mongo config. But if that's the case, why does it work on Mac?

I am certain Mongo is running on the correct port on the host:

net: { bindIp: '127.0.0.1', port: 27017 }

So I am not entirely sure what is going on here. Could someone explain why I can't connect to the host's mongo database and what would be the best way to solve it without compromising any security?

Upvotes: 0

Views: 284

Answers (1)

Bram  Vanbilsen
Bram Vanbilsen

Reputation: 6505

After looking more into this, I did had to add 172.17.0.1 to my mongod.conf file to make it work:

net:
  port: 27017
  bindIp: 127.0.0.1, 172.17.0.1

This makes sense, as before it would only allow localhost connections.
As for why it did work on my Mac, the config did allow connections from that address already!

Upvotes: 0

Related Questions