Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to host mongodb from docker container

So I want to connect to my mongodb running on my host machine (DO droplet, Ubuntu 16.04). It is running on the default 27017 port on localhost.

I then use mup to deploy my Meteor app on my DO droplet, which is using docker to run my Meteor app inside a container. So far so good. A standard mongodb://... connection url is used to connect the app to the mongodb. Now I have the following problem:

mongodb://...@localhost:27017... obviously does not work inside the docker container, as localhost is not the host's localhost.

I already read many stackoverflow posts on this, I already tried using:

  • --network="host" - did not work as it said 0.0.0.0:80 is already in use or something like that (nginx proxy)
  • --add-host="local:<MY-DROPLET-INTERNET-IP>" and connect via mongodb://...@local:27017...: also not working as I can access my mongodb only from localhost, not from the public IP

This has to be a common problem!

tl;dr - What is the proper way to expose the hosts localhost inside a docker container so I can connect to services running on the host? (including their ports, e.g. 27017).

I hope someone can help!

like image 953
Patrick DaVader Avatar asked Aug 02 '17 12:08

Patrick DaVader


People also ask

How does MongoDB run in Docker container from host?

You can connect to MongoDB on localhost:27017 . Then use the following command to open the MongoDB shell. I have used mymongo as an arbitrary container name, though you can replace mymongo with test-mongo or any other container name of your choosing. The show dbs command will display all your existing databases.

How can I access a MongoDB container from another container?

If you need to access the MongoDB server from another application running locally, you will need to expose a port using the -p argument. Using this method, you will be able to connect to your MongoDB instance on mongodb://localhost:27017 . You can try it with Compass, MongoDB's GUI to visualize and analyze your data.

How does MongoDB connect to local host?

To connect to your local MongoDB, you set Hostname to localhost and Port to 27017 . These values are the default for all local MongoDB connections (unless you changed them). Press connect, and you should see the databases in your local MongoDB.


2 Answers

You can use: 172.17.0.1 as it is the default host ip that the containers can see. But you need to configure Mongo to listen to 0.0.0.0.

From docker 18.03 onwards the recommendation is to connect to the special DNS name host.docker.internal

For previous versions you can use DNS names docker.for.mac.localhost or docker.for.windows.localhost.

like image 193
Robert Avatar answered Oct 21 '22 01:10

Robert


change the bindIp from 127.0.0.1 to 0.0.0.0 in /etc/mongod.conf. Then it will work

like image 29
Siva S Avatar answered Oct 21 '22 01:10

Siva S