我正在使用带有 NodeJS 后端的 mongoDB。问题是我收到以下错误
node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
这是我的 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
,但没有用。
在后端,我是作为与 DB 通信的中间件的 Mongoose 。这是我的 index.js
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost/demo')
app.listen(port, () => console.log("live"))
我也尝试过使用 promise ,但没有任何变化。请帮帮我。 在此先感谢
完整的错误日志
at Pool. (/app/node_modules/mongodb-core/lib/topologies/server.js:505:11) rest-api-node_1 | at Pool.emit (events.js:180:13) rest-api-node_1 | at Connection. (/app/node_modules/mongodb-core/lib/connection/pool.js:329:12) rest-api-node_1 | at Object.onceWrapper (events.js:272:13) rest-api-node_1 | at Connection.emit (events.js:180:13) rest-api-node_1 | at Socket. (/app/node_modules/mongodb-core/lib/connection/connection.js:245:50) rest-api-node_1 | at Object.onceWrapper (events.js:272:13) rest-api-node_1 | at Socket.emit (events.js:180:13) rest-api-node_1 | at emitErrorNT (internal/streams/destroy.js:64:8) rest-api-node_1 | at process._tickCallback (internal/process/next_tick.js:178:19) rest-api-node_1 | name: 'MongoNetworkError', rest-api-node_1 |
message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
最佳答案
By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
根据您的 docker-compose.yaml
文件,您只能从主机访问 127.0.0.1:27017
上的 mongo 容器。
为了从 NodeJS 后端容器访问它,您应该使用 db:27017
。
关于node.js - MongoDB 与 Docker "failed to connect to server [localhost:27017] on first connect ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011552/