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
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))
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!