我有一个在mongodb://127.0.0.1:27017上运行的本地mongoDB服务器.我的数据库名称是 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.jsserver.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
请帮助.
推荐答案在Mac的Docker上,如果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-aroundarounds
See here for more details on docs.docker/docker-for-mac/networking/#use-cases-and-workarounds
更多推荐
从docker容器连接到本地mongodb
发布评论