Home > Backend Development > Golang > How can I connect a Go application in a Docker container to a local MongoDB instance?

How can I connect a Go application in a Docker container to a local MongoDB instance?

Linda Hamilton
Release: 2024-11-16 19:07:03
Original
1017 people have browsed it

How can I connect a Go application in a Docker container to a local MongoDB instance?

Dockerizing Go App with Local Mongo Connection

When working on Golang projects with Docker, integrating a local MongoDB database poses a connectivity challenge. If a Go project using MongoDB is run outside Docker, the database connection is successful. However, when the same project is run within a Docker container, the connection fails.

Understanding the Issue

Docker creates a virtual environment for containerized applications. This means that the container runs in a separate network space, distinct from the host system. Consequently, connecting to external resources, such as a locally running MongoDB instance, becomes problematic.

Solution: Utilizing host.docker.internal

Docker assigns a unique IP address to each container and provides a special hostname, "host.docker.internal." This hostname acts as a gateway to connect to the host system from within the container. Since MongoDB is running locally on the host system, using "host.docker.internal" as its hostname resolves the connectivity issue.

Modified Dockerfile

To incorporate this solution, modify the Dockerfile as follows:

FROM golang
WORKDIR $GOPATH/src/myapp
ADD . /go/src/myapp
RUN go get ./...
RUN go install myapp
ENV MONGO_HOST=host.docker.internal
CMD /go/bin/myapp --mongodbhost=$MONGO_HOST
EXPOSE 8080
EXPOSE 27017
Copy after login

Connection String

Within the Go application, update the MongoDB connection string to use "host.docker.internal" as the hostname. For example:

connectionString := fmt.Sprintf("mongodb://host.docker.internal:21017/database")
client, err := mongo.Connect(ctx, options.Client().ApplyURI(connectionString))
Copy after login

The above is the detailed content of How can I connect a Go application in a Docker container to a local MongoDB instance?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template