Babak Abadkheir
Babak Abadkheir

Reputation: 2358

connect to mongodb from docker

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.

Upvotes: 0

Views: 74

Answers (1)

Adam Coster
Adam Coster

Reputation: 1472

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.

Upvotes: 1

Related Questions