无法将mongodb容器连接到docker中的节点容器

Sam*_*ngh 2 ip tcp mongoose mongodb docker

我用这个仓库中的 2 个镜像和 1 个使用 MongoDB 公共镜像制作了 3 个 docker 容器。我使用以下命令打开了所有三个容器sudo docker-compose -f docker-compose.yaml up

docker-compose.yaml是:

version: '3'
services:
  frontend:
    image: samar080301/mern-frontend:1.0
    ports:
      - 3000:3000
  backend:  
    image: samar080301/mern-backend:1.0
    ports:
      - 5000:5000
  mongodb:
    image: mongo:latest
    ports:
      - 27017:27017
Run Code Online (Sandbox Code Playgroud)

但是 MongoDB 无法连接到节点服务器并给出以下错误:

backend_1   | > crud-app@1.0.0 start /home/app
backend_1   | > node server.js
backend_1   | 
backend_1   | (node:18) 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.
backend_1   | (Use `node --trace-deprecation ...` to show where the warning was created)
backend_1   | App running on port 5000
backend_1   | Error with the database! MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
backend_1   |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
backend_1   |   name: 'MongoNetworkError'
backend_1   | }]
backend_1   |     at Pool.<anonymous> (/home/app/node_modules/mongodb/lib/core/topologies/server.js:438:11)
backend_1   |     at Pool.emit (events.js:315:20)
backend_1   |     at /home/app/node_modules/mongodb/lib/core/connection/pool.js:562:14
backend_1   |     at /home/app/node_modules/mongodb/lib/core/connection/pool.js:995:11
backend_1   |     at /home/app/node_modules/mongodb/lib/core/connection/connect.js:32:7
backend_1   |     at callback (/home/app/node_modules/mongodb/lib/core/connection/connect.js:280:5)
backend_1   |     at Socket.<anonymous> (/home/app/node_modules/mongodb/lib/core/connection/connect.js:310:7)
backend_1   |     at Object.onceWrapper (events.js:422:26)
backend_1   |     at Socket.emit (events.js:315:20)
backend_1   |     at emitErrorNT (internal/streams/destroy.js:84:8)
backend_1   |     at processTicksAndRejections (internal/process/task_queues.js:84:21)
backend_1   | (node:18) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
backend_1   |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
backend_1   |   name: 'MongoNetworkError'
backend_1   | }]

Run Code Online (Sandbox Code Playgroud)

代码backend/db.js

const mongoose = require('mongoose');
// Allow Promises
mongoose.Promise = global.Promise;
// Connection
mongoose.connect('mongodb://localhost:27017/db_test', { useNewUrlParser: true });
// Validation
mongoose.connection
  .once('open', () => console.log('Connected to the database!'))
  .on('error', err => console.log('Error with the database!', err));
Run Code Online (Sandbox Code Playgroud)

终端输出docker inspect mongodb在此输入图像描述

添加 mongo uri 作为环境变量后的终端输出:

backend_1   | App running on port 5000
backend_1   | (node:19) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
backend_1   | (node:19) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
Run Code Online (Sandbox Code Playgroud)

新错误:

backend_1   | Error with the database! MongoNetworkError: failed to connect to server [merncrudapp_mongodb_1:27017] on first connect [Error: connect ECONNREFUSED 172.23.0.3:27017
backend_1   |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
backend_1   |   name: 'MongoNetworkError'
backend_1   | }]
Run Code Online (Sandbox Code Playgroud)

Ste*_*ich 5

当您运行 docker-compose up 时,会发生以下情况:

\n
    \n
  1. MernCrudApp创建一个名为(采用目录的默认名称)的网络。
  2. \n
  3. frontend使用\ 的配置创建容器。MernCrudApp它以 的名义加入网络frontend
  4. \n
  5. backend使用\ 的配置创建容器。MernCrudApp它以 的名义加入网络backend
  6. \n
  7. 使用 \xe2\x80\x99s 配置创建容器mongodbMernCrudApp它以 的名义加入网络mongodb
  8. \n
\n

现在,如果您使用mongodb://localhost:27017/db_test连接到数据库,节点应用程序将在后端容器中查找 MongoDB,您将收到连接错误,因为它不存在。

\n

要解决此问题,请将 MongoDB 连接字符串更改mongodb://mongodb:27017/db_test

\n

其他评论
\n我建议以下内容来帮助解决您将来使用当前配置可能遇到的一些问题。

\n
    \n
  1. 将连接字符串添加为环境变量。这将使您可以更轻松地更改数据库实例,而无需重建容器。
  2. \n
  3. 由于后端应用程序依赖于数据库,因此depend_on在 docker-compose 文件上添加数据库,以便 MongoDB 容器在后端容器之前启动
  4. \n
\n