【发布时间】:2020-04-24 15:54:01
【问题描述】:
情况:
我制作了一个小型 Web (node.js) 应用程序的原型并将其 docker 化以用于部署和可复制性目的。
该应用与直接在主机上运行的 MongoDB 对话。
问题:
在服务器上(AWS EC2 实例,仅开放 80 和 443 端口),我无法与 MongoDB 交互,我想知道为什么。
docker run --net="host" -e 'NODE_ENV=production' -e 'MONGO_URI=mongodb://USER:PASSWORD!@172.31.32.1:27017/test_db' DOCKER_IMAGE
MongoDB connected ...
Warning: connect.session() MemoryStore is not
designed for a production environment, as it will leak
memory, and will not scale past a single process.
HTTP Server started on port 80
(node:1) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [172.31.32.1:27017] on first connect [MongoNetworkError: connection timed out
at connectionFailureError (/app/server/node_modules/mongodb/lib/core/connection/connect.js:377:14)
at Socket.<anonymous> (/app/server/node_modules/mongodb/lib/core/connection/connect.js:287:16)
at Object.onceWrapper (events.js:284:20)
at Socket.emit (events.js:196:13)
at Socket._onTimeout (net.js:432:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: {}
}]
at Pool.<anonymous> (/app/server/node_modules/mongodb/lib/core/topologies/server.js:433:11)
at Pool.emit (events.js:196:13)
at /app/server/node_modules/mongodb/lib/core/connection/pool.js:571:14
at /app/server/node_modules/mongodb/lib/core/connection/pool.js:994:11
at /app/server/node_modules/mongodb/lib/core/connection/connect.js:40:11
at callback (/app/server/node_modules/mongodb/lib/core/connection/connect.js:262:5)
at Socket.<anonymous> (/app/server/node_modules/mongodb/lib/core/connection/connect.js:287:7)
at Object.onceWrapper (events.js:284:20)
at Socket.emit (events.js:196:13)
at Socket._onTimeout (net.js:432:8)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: {}
}
我最初尝试使用localhost 而不是 IP 地址,但这不起作用。它会引发身份验证错误(这有点奇怪)。由于 Linux 没有host.docker.internal,我不得不(暂时)解析为显式 IP 地址。我使用的IP地址我得到了via:
netstat -nr | grep '^0\.0\.0\.0' | awk '{print $2}'
我觉得很奇怪的是,我没有收到身份验证错误,而是出现超时错误,所以对我来说,该应用程序似乎能够连接到 Mongo。此外,“MonogDB connected ...”将表明,因为它是由我的服务器脚本中的以下行生成的。
mongoose
.connect(DB, { useNewUrlParser: true })
.then(console.log("MongoDB connected ..."))
.catch(err => console.log(err));
为了完整起见,相同的设置(即 dockerized 应用程序和直接在主机上运行 MongoDB)在本地运行没有问题。
另外,我可以通过mongo进入服务器上的Mongo Shell。
感谢任何解释或提示!
【问题讨论】:
标签: node.js mongodb amazon-web-services docker mongoose