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

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

DDD
Release: 2024-11-20 12:22:10
Original
555 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template