Home > Net >  How to connect to MongoDB running in local machine from a docker container?
How to connect to MongoDB running in local machine from a docker container?

Time:08-24

I have a docker container running a spring-boot application for which i plan to use the mongoDb in my local machine.I know that containers are on a different network, and have made the necessary changes in the /etc/mongod.conf file as suggested by https://tsmx.net/docker-local-mongodb/ , in order for mongodb to accept connections from the docker network. But still the connection times out when the connection attempt is made from the docker container. Any help is appreciated.

CodePudding user response:

You need to check the network interfaces of your host. You should find one starting with 192.168 or similar. Make sure your MongoDb instance is listening on this interface.

When you run the container, add --add-host mongodb:192.168.X.X to the docker run command. Replace the IP you find at the previous point.

docker run --help | grep add-host
      --add-host list                  Add a custom host-to-IP mapping (host:ip)

Now in your Spring Boot application you can look for your MongoDB server called mongodb.

CodePudding user response:

`docker run -d --add-host=host.docker.internal:host-gateway --name xxx -p 4001:4000 xxx` 

above command gives access of local host of server to docker container. Now when you connect to mongodb from inside docker container access it like this

let uri = "mongodb://host.docker.internal:27017"

Here 27017 is default port of mongodb

  • Related