从 docker 容器连接到本地 mongodb [英] connecting to local mongodb from docker container

查看:49
本文介绍了从 docker 容器连接到本地 mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本地 mongoDB 服务器在 mongodb://127.0.0.1:27017 上运行.我的数据库名称是 localv2.我有一个带有 Dockerfile 的 node/express 应用程序,如下所示:

I have a local mongoDB server running on mongodb://127.0.0.1:27017. My DB name is localv2. I have a node/express app with the Dockerfile as follows:

FROM node:7.5

RUN npm install -g pm2

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app
RUN npm install

COPY . /usr/src/app

EXPOSE 3002

ENV NODE_ENV local

CMD pm2 start --no-daemon server.js

server.js 文件通过以下代码连接到本地 mongodb:

The server.js file has a connection to local mongodb with the following code:

app.db = mongoose.connect("mongodb://127.0.0.1:27017/localv2", options);

当我从使用上面的 Dockerfile 创建的映像启动容器时,这不起作用.我在某处读到 Docker 创建了一个具有自己网关 IP 地址的 VLAN.当我 docker inspect 我的容器时,我的网关 IP 地址:172.17.0.1.

This doesn't work when I spin up a container from the image created using the Dockerfile above. I read somewhere that Docker creates a VLAN with a gatway IP address of its own. When I docker inspect my container, my gateway IP address: 172.17.0.1.

即使将 mongodb 连接更改为

Even on changing the mongodb connection to

app.db = mongoose.connect("mongodb://172.17.0.1:27017/localv2", options)

并重新构建映像并启动一个新容器,我仍然收到错误:

and re-building the image and starting a new container, I still get the error:

MongoError: failed to connect to server [172.17.0.1:27017] on first connect [MongoError: connect ECONNREFUSED 172.17.0.1:27017]

运行容器的命令:docker run -p 3002:3002 image-name

请帮忙.

推荐答案

在 Docker for Mac 上,如果你的 mongo 在你的本地主机上运行,​​你可以使用 host.docker.internal.您可以在 mongo 主机的 env 变量中读取代码并将其设置在 Dockerfile 中,如下所示:

On Docker for Mac, you can use host.docker.internal if your mongo is running on your localhost. You could have your code read in an env variable for the mongo host and set it in the Dockerfile like so:

ENV MONGO_HOST "host.docker.internal"

查看此处了解更多详情https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds

这篇关于从 docker 容器连接到本地 mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆