【问题标题】:Error when nodejs app in a docker container tries to connect to mongodb in a different docker container当 docker 容器中的 nodejs 应用程序尝试连接到不同 docker 容器中的 mongodb 时出错
【发布时间】:2020-10-16 08:35:21
【问题描述】:

我正在尝试让我的 nodejs API 在 docker 容器中运行,以连接到在不同容器中运行的 mongodb。

当我运行命令 docker ps 时,我得到以下输出:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
2ad1f567f713        mongo               "docker-entrypoint.s…"   6 hours ago         Up 24 minutes       0.0.0.0:27017->27017/tcp   mongodb

然后我运行了这个命令docker run --publish 3000:3000 --name my-api my-api:1.0,但这给了我这个超时错误

(node:37) UnhandledPromiseRejectionWarning: MongoTimeoutError: Server selection timed out after 30000 ms

然后我尝试了这个命令 docker run --publish 3000:3000 --net 2ad1f567f713:mongodb --name my-api my-api:1.0,但出现了这个错误:

docker: Error response from daemon: network 2ad1f567f713:mongodb not found.

我做错了什么?

【问题讨论】:

标签: node.js mongodb docker


【解决方案1】:

根据@DavidMaze 链接,我做了以下事情:

首先,在我的my-api nodejs 代码中,我必须将我的.env 文件从

MONGODB_URL=mongodb://@127.0.0.1:27017/hellodatabase?retryWrites=true&w=majority

MONGODB_URL=mongodb://@mongodb:27017/hellodatabase?retryWrites=true&w=majority

请注意@mongodb,我打算稍后在我的回答中将其用作容器名称。

然后我做了

// start network called hello-network
docker create network hello-network;
// start mongo database on the hello-network, run in background, mount database to my localhost drive /data/db, and also call this instance mongodb to match my earlier .env file
docker run -it --publish 27017:27017 --network hello-network -v mongodata:/data/db --name mongodb -d mongo;
// start my-api on the hello-network, in the background
docker run -it --publish 3000:3000 --network hello-network -d --name my-api my-api:1.0;

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 2020-07-21
    • 2019-01-04
    • 2018-12-04
    • 2018-08-30
    • 2019-04-14
    • 1970-01-01
    • 2017-11-10
    • 2017-10-13
    相关资源
    最近更新 更多