如何将本地Mongo数据库连接到docker

问题描述 投票:-1回答:2

我正在研究golang项目,最近我读到了有关do​​cker并尝试使用docker和我的应用程序。我正在使用mongoDB数据库。现在的问题是,我正在创建Dockerfile来安装所有包并编译并运行go项目。我在本地运行mongo数据,如果我正在运行没有docker的程序它给我输出,但是如果我使用docker用于同一个项目(只是用这个和运行项目安装依赖项),它编译成功但不提供任何输出,有错误::

CreateSession: no reachable servers 

我的Dockerfile ::

# Start from a Debian image with the latest version of Go installed
# and a workspace (GOPATH) configured at /go.
FROM golang
WORKDIR $GOPATH/src/myapp

# Copy the local package files to the container's workspace.
ADD . /go/src/myapp

#Install dependencies
RUN go get ./...

# Build the installation command inside the container.
RUN go install myapp

# Run the outyet command by default when the container starts.
ENTRYPOINT /go/bin/myapp

# Document that the service listens on port 8080.
EXPOSE 8080
EXPOSE 27017
mongodb docker go
2个回答
2
投票

在Docker中运行应用程序时,它在虚拟环境中运行;它就像另一台计算机,但一切都是虚拟的,包括网络。

为了将容器连接到主机,Docker为它提供了一个特殊的ip地址,并为此ip提供了一个值为host.docker.internal的url。

因此,假设mongo在主机上的每个接口上都运行绑定,从容器可以通过连接字符串到达​​:

MongoDB的://host.docker.internal:21017 /数据库

简化,Just use host.docker.internal as your mongodb hostname.


1
投票

在golang项目中,如何指定与mongodb的连接?本地主机:27017?

如果您在代码中使用localhost,您的docker容器将是localhost,并且由于您在同一容器中没有mongodb,您将收到错误。

如果您使用命令行docker run ...启动docker,请添加--network="host"。如果您使用的是docker-compose,请添加network_mode: "host"

理想情况下,您可以在自己的容器中设置mongodb并从docker-compose.yml连接它们 - 但这不是您要求的。所以,我不会进入那个。

在以后的问题中,请尽可能包含相关的Dockerfile,docker-compose.yml。它将帮助我们提供更具体的答案。

© www.soinside.com 2019 - 2024. All rights reserved.