问题描述
我正在使用 mongoDB 和 NodeJS 后端.问题是我收到以下错误
I am using mongoDB with and NodeJS backend. The Problem is I am getting the following error
node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed在第一次连接时连接到服务器 [localhost:27017][MongoNetworkError:连接ECONNREFUSED 127.0.0.1:27017]
这是我的 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.
在后端,我使用猫鼬作为与数据库通信的中间件.这是我的 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
完整的错误日志
在游泳池.(/app/node_modules/mongodb-core/lib/topologies/server.js:505:11)rest-api-node_1 |在 Pool.emit (events.js:180:13) rest-api-node_1|在连接.(/app/node_modules/mongodb-core/lib/connection/pool.js:329:12)rest-api-node_1 |在 Object.onceWrapper (events.js:272:13)rest-api-node_1 |在 Connection.emit (events.js:180:13)rest-api-node_1 |在套接字.(/app/node_modules/mongodb-core/lib/connection/connection.js:245:50)rest-api-node_1 |在 Object.onceWrapper (events.js:272:13)rest-api-node_1 |在 Socket.emit (events.js:180:13)rest-api-node_1 |在发射错误NT(internal/streams/destroy.js:64:8) rest-api-node_1 |在process._tickCallback (internal/process/next_tick.js:178:19)rest-api-node_1 |名称:'MongoNetworkError',rest-api-node_1 |
消息:'第一次连接到服务器 [localhost:27017] 失败连接 [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
推荐答案
根据您的 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]"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!