Docker containers run in an isolated environment including separate virtual networks by default. Although you can run your MongoDB in a container connected to such a virtual network, e.g. by using docker-compose, there may be situations where you want to use a local MongoDB instance and connect to it from a container.
The Docker bridge network
To establish networking connections between the host and containers, a Docker bridge network can be used. A standard one called bridge is always present and generated by default. You can inspect it using the docker network inspect bridge command.Notice that this network has a Gateway with IP 172.17.0.1. This we will use to connect from the container to our MongoDB running on the host.
According to the Docker docs on networking the default bridge network should not be used for production scenarios but is fine for any dev/test environment. In this article, we will continue using the default bridge.
Connecting to your local MongoDB from Docker
For connecting to your local MongoDB instance from a Container you must first allow to accept connections from the Docker bridge gateway. To do so, simply add the respective gateway IP in the MongoDB config file /etc/mongod.conf under bindIp in the network interface section. Note that binding to 0.0.0.0 would also do the trick but is not recommended due to security reasons.Second, you should choose a hostname to access the database. Let’s use mongoservice for that. In your containerized app, use this hostname in the connection string, like so… To introduce the mongo service hostname in the containers virtual network and bind it to our local host where MongoDB is running, simply use the --add-host option of docker run with the bridge networks gateway IP we discovered earlier. Having this in place, your Docker container now can communicate with the host using the alias mongo service and you are good to go in connecting to the local MongoDB.
Tip: using the identical hostname alias for MongoDB locally
To avoid inconsistencies and configuration changes between running your app in the local dev environment and the Docker container, simply add an entry for the used hostname mongo service to your /etc/hosts.Now you can use the exactly same connection string also in your local dev environment.