Reputation: 127
I have a mongo on my host machine, and an ubuntu container which is also running on my machine. I want that container to connect to mongo. I set as host url, my host ip from docker network : 172.17.0.1 and in the /etc/mongod.conf file I set the bindIp to 0.0.0.0
from the container, I can ping the host,but the mongo service is not accessible, I get that error :
Connecting to: mongodb://172.17.0.1:27017/directConnection=true&appName=mongosh+1.5.0
MongoServerSelectionError: connection timed out
More over, I can connect from host to the mongo service with that command :
mongosh mongodb://172.17.0.1:27017
Do you know why I can't access mongo service from my container ?
Upvotes: 2
Views: 6459
Reputation: 185620
Do not use
0.0.0.0
to bind a socket on your host. It can be a security issue. It's the way to declare all IP are able to connect to mongodb
from any host.
Better edit /etc/mongod.conf
and add the docker
interface ip, like:
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1,172.17.0.1
Then, in the docker run
, you can add a host:
docker run --add-host mongohost:172.17.0.1 <CONTAINER>
Now, in your container, you can query mongohost
on port 27017
.
This is the clean solution.
You can also use extra_hosts
if you use docker-compose
.
But, Docker Compose is primarily designed for local development and testing purposes.
According to the official Docker documentation, if you insist to use it, use V2 and a special production.yaml
Upvotes: 3
Reputation: 2176
You can use host.docker.internal
as reference to your host machine from the container. So mongo host.docker.internal:27017
should work.
From docker documentation:
I want to connect from a container to a service on the host The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name host.docker.internal which resolves to the internal IP address used by the host. This is for development purpose and does not work in a production environment outside of Docker Desktop.
This solution is not provided for every docker
environments. docker desktop
have this feature unlike basic Linux environment.
Upvotes: 2
Reputation: 387
On your local machine that has Mongo service is running, you can access by Mongo client because you expose the service at 127.0.0.1:27017
.
However, it is not true if standing from your unbuntu
container, there is no Mongo service is running at 172.0.0.1:27017
of the ubuntu
container.
Docker-compose is the right tool for you to make containers communication to each other.
Upvotes: -1