0

i have a MongoDB running in my host with ip 127.0.0.1:27017 . I need to connect to my MongoDB from the docker image. so I try with these addresses:

localhost:27017

0.0.0.0:27017

but I get connection refused. is it about mongodb auth ?I didnt enable mongodb authentication on my host yet.

1
  • 2
    From the perspective if the running Docker container localhost is the container, not your docker host. Check out this post on one possibel way to connect to the Docker host: forums.docker.com/t/… Commented Apr 21, 2020 at 13:16

1 Answer 1

1

As Ralf said in your comments, "localhost" from inside your container refers to the container itself.

An option to get around this is to also run MongoDB in a container, and then use docker-compose to run both containers and have them talk to each other.

For example, your (stripped-down, incomplete) docker-compose.yml file would look something like:

version: "3.3"
services:
  mongo:
    image: mongo:4.0.11-xenial
    ports:
      - 27017:27017
  your-app:
    # settings dependant on whatever your app is
    depends_on:
      - mongo

Then when you are trying to connect via your application, you can connect using mongodb://<user>:<pass>@mongo/YourDatabase, since Docker will map mongo onto your mongo service.

Sign up to request clarification or add additional context in comments.

2 Comments

So is there actually now way of connecting to a db that is running in the docker host? The only way I was able to get it working was by binding 0.0.0.0 and using the full host static IP in the mongo db url. But of course this is a security issue, so I don't want that.
The only way I know is the docker-compose approach described above, but that only works if your app and database are both running in the same virtual network created by Docker (e.g. by launching both via docker-compose).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.