从 docker 容器连接到本地 mongodb

编程入门 行业动态 更新时间:2024-10-28 09:28:11
本文介绍了从 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"

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

更多推荐

从 docker 容器连接到本地 mongodb

本文发布于:2023-10-14 12:27:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1491055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   容器   docker   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!