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

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

本文介绍了如何将本地Mongo数据库连接到Docker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究golang项目,最近我阅读了有关do​​cker的信息,并尝试在我的应用程序中使用docker。我将mongoDB用于数据库。
现在的问题是,我正在创建Dockerfile来安装所有软件包并编译和运行go项目。
我在本地运行mongo数据,如果我在没有docker的情况下运行go程序,它会给我输出,但是如果我在同一项目中使用docker(只需为此项目安装依赖项并运行项目),则编译成功但未成功给出任何输出,但有错误:

I am working on golang project, recently I read about docker and try to use docker with my app. I am using mongoDB for database.Now problem is that, I am creating Dockerfile to install all packages and compile and run the go project.I am running mongo data as locally, if I am running go program without docker it gives me output, but if I am using docker for same project (just installing dependencies with this and running project), it compile successfully but not gives any output, having error::

CreateSession: no reachable servers

我的Dockerfile ::

my 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


推荐答案

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

When you run your application inside Docker, it's running in a virtual environment; It's just like another computer but everything is virtual, including the network.

要将容器连接到主机,Docker会为其提供一个特殊的IP地址并为该IP提供一个url值 host.docker.internal

To connect your container to the host, Docker gives it an special ip address and give this ip an url with the value host.docker.internal.

因此,假设mongo在绑定的每个接口上运行主机,可以通过连接字符串从容器中访问它:

So, assuming that mongo is running with binding on every interface on the host machine, from the container it could be reached with the connection string:

简化,只需使用host.docker.internal作为您的mongodb主机名。

这篇关于如何将本地Mongo数据库连接到Docker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:43