node.js - Docker MongoNetworkError : connection timed out when build Node JS App by docker

标签 node.js mongodb docker docker-compose dockerfile

无法连接到 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:连接超时

    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.

最佳答案

mongo 安装在 container 上所以请确保:

  1. 运行构建容器时暴露27017端口,

    docker run -p 27017:27017 ....

  2. node 代码中,连接到 mongo 容器使用:容器网络的 IP 地址网关是 172.17.0.1:27017

所以:

let dbRoute = "mongodb://172.17.0.1:27017/kgp_news"

关于node.js - Docker MongoNetworkError : connection timed out when build Node JS App by docker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962414/

相关文章:

mongodb - Fiware天鹅座: Can we store Orion data in MongoDB under other types than String?

mongodb - 设置复合索引时出错

mongodb 3.4.2 InvalidIndexSpecificationOption错误: The field 'unique' is not valid for an _id index specification

c# - 在 Windows Server Core Docker 上安装 .NET Framework 3.5

node.js - 开源程序中的加密?

javascript - 我如何在路由模型nodejs中获取获取的记录

amazon-web-services - Amazon EB中的Dockerfile

docker - Flink 1.7.0仪表板不显示任务统计信息

node.js - 这两种服务 React App 的方式有什么区别?

javascript - Mongodb,如何对1个对象进行多个请求