无法连接到Mongodb。由Docker安装的
let dbRoute = "mongodb://mongo:27017/kgp_news"
const option = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000,
useNewUrlParser: true
};
mongoose.connect(dbRoute, option)
我通过docker安装mongo。运行端口27017。
当我通过脚本“ node index.js”运行项目时。它正在工作。
但是当我通过编写Dockerfile构建应用程序时。无法连接到Mongo。
MongoNetworkError: connection timed out
at Pool.<anonymous> (/api_kgp/docker_build/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (/api_kgp/docker_build/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at makeConnection (/api_kgp/docker_build/node_modules/mongodb-core/lib/connection/connect.js:39:11)
at callback (/api_kgp/docker_build/node_modules/mongodb-core/lib/connection/connect.js:261:5)
at Socket.err (/api_kgp/docker_build/node_modules/mongodb-core/lib/connection/connect.js:286:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at Socket._onTimeout (net.js:442:8)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
(node:20) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
答案 0 :(得分:0)
使用localhost
的Docker容器正在运行。
let dbRoute = "mongodb://localhost:27017/kgp_news"
const option = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000,
useNewUrlParser: true
};
mongoose.connect(dbRoute, option)
或者,您可以输入mongodb condtiner的IP地址。要从mongodb conatiner中删除IP,请使用$ docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $INSTANCE_ID
let dbRoute = "mongodb://<MONGODB_IP_ADDRESS>:27017/kgp_news"
const option = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000,
useNewUrlParser: true
};
mongoose.connect(dbRoute, option)
答案 1 :(得分:0)
mongo
已安装在container
上,因此请确保:
运行27017
时公开container
端口
docker run -p 27017:27017 ....
在node
代码中,使用以下命令连接到mongo
容器:容器网络的IP地址网关为172.17.0.1:27017
所以:
let dbRoute = "mongodb://172.17.0.1:27017/kgp_news"