问题描述
我将MongoDB与NodeJS后端一起使用.问题是我遇到以下错误
I am using mongoDB with and NodeJS backend. The Problem is I am getting the following error
这是我的docker-compose
This is my docker-compose
version: '3.4'
services:
db:
image: mongo:latest
ports:
- '27017:27017'
rest-api-node:
build: .
ports:
- '5000:5000'
links:
- db
restart: on-failure
我也尝试过使用depends_on
,但是没有用.
I have tried with depends_on
as well , was not working.
在后端,我很猫鼬作为与DB通信的中间件.这是我的index.js
On backend I am mongoose as a middleware to communicate with DB. this is the part of my index.js
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost/demo')
app.listen(port, () => console.log("live"))
我也尝试过使用promise,尽管没有变化.请帮帮我.预先感谢
I have tried using promise as well , no change though. Please Help me out.Thanks in advance
完整的错误日志
推荐答案
根据您的docker-compose.yaml
文件,您只能从主机访问127.0.0.1:27017
上的mongo容器.为了从NodeJS后端容器访问它,您应该使用db:27017
.
According to your docker-compose.yaml
file you can access you mongo container on 127.0.0.1:27017
only from host machine. In order to access it from NodeJS backend container you should use db:27017
.
这篇关于使用Docker的MongoDB在“第一次连接时无法连接到服务器[localhost:27017]"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!