Home  >  Article  >  Backend Development  >  How to Connect a Docker Container to a Local MongoDB Database?

How to Connect a Docker Container to a Local MongoDB Database?

DDD
DDDOriginal
2024-11-20 12:22:10483browse

How to Connect a Docker Container to a Local MongoDB Database?

Connecting Local Mongo Database to Docker

When running a Docker container, it establishes a virtual network environment, isolating the container from the host system. This can cause challenges when accessing external resources, such as local databases. Here's how to address the issue when using MongoDB during containerization.

Docker assigns a unique IP address to each container. To connect to a local Mongo database from within a container, it's essential to use this special IP address, which is accessible via the URL host.docker.internal.

Assuming MongoDB is configured to listen on all interfaces on the host machine, the container can reach it using the following connection string:

mongodb://host.docker.internal:21017/database

Simply replace the hostname field with host.docker.internal in the MongoDB connection URL to establish the connection from the container to the local Mongo database. By using host.docker.internal, you can bridge the gap between the isolated container network and the host network, resolving the "no reachable server" error.

The above is the detailed content of How to Connect a Docker Container to a Local MongoDB Database?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn