简体   繁体   English

在 Docker Compose 中获取“MongooseServerSelectionError:连接 ECONNREFUSED 127.0.0.1:27017”

[英]Getting "MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017" in Docker Compose

I am doing a REST API with Express and MongoDB.我正在用 Express 和 MongoDB 做 REST API。 Everything works perfectly locally.一切都在本地完美运行。 I want to dockerize the database and the backend using Docker Compose.我想使用 Docker Compose 对接数据库和后端。

The Mongo Docker works perfectly, but the backend fails to connect to it. Mongo Docker 完美运行,但后端无法连接到它。 It keeps throwing me this error:它不断向我抛出这个错误:

/backend/node_modules/mongoose/lib/connection.js:797

  const serverSelectionError = new ServerSelectionError();

                               ^


MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

    at NativeConnection.Connection.openUri (/backend/node_modules/mongoose/lib/connection.js:797:32)

    at /backend/node_modules/mongoose/lib/index.js:341:10

    at /backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5

    at new Promise (<anonymous>)

    at promiseOrCallback (/backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)

    at Mongoose._promiseOrCallback (/backend/node_modules/mongoose/lib/index.js:1167:10)

    at Mongoose.connect (/backend/node_modules/mongoose/lib/index.js:340:20)

    at Object.<anonymous> (/backend/index.js:11:3)

    at Module._compile (node:internal/modules/cjs/loader:1097:14)

    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) {

  reason: TopologyDescription {

    type: 'Unknown',

    servers: Map(1) {

      'localhost:27017' => ServerDescription {

        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },

        address: 'localhost:27017',

        type: 'Unknown',

        hosts: [],

        passives: [],

        arbiters: [],

        tags: {},

        minWireVersion: 0,

        maxWireVersion: 0,

        roundTripTime: -1,

        lastUpdateTime: 14312460,

        lastWriteDate: 0,

        error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

            at connectionFailureError (/backend/node_modules/mongodb/lib/cmap/connect.js:293:20)

            at Socket.<anonymous> (/backend/node_modules/mongodb/lib/cmap/connect.js:267:22)

            at Object.onceWrapper (node:events:510:26)

            at Socket.emit (node:events:390:28)

            at emitErrorNT (node:internal/streams/destroy:164:8)

            at emitErrorCloseNT (node:internal/streams/destroy:129:3)

            at processTicksAndRejections (node:internal/process/task_queues:83:21)

      }

    },

    stale: false,

    compatible: true,

    heartbeatFrequencyMS: 10000,

    localThresholdMS: 15,

    logicalSessionTimeoutMinutes: undefined

  }

}

I've read online that the issue could be that I shouldn't connect to localhost but to the MongoDB container.我在网上读到问题可能是我不应该连接到本地主机,而是连接到 MongoDB 容器。

I attach the files:我附上文件:

docker-compose.yml docker-compose.yml

version: '3.8'

services:
    data:
      container_name: data
      image: mongo
      ports:
        - 27017:27017
      volumes:
        - ./data/db:/data/db
    
    backend:
      container_name: backend
      depends_on:
        - data
      build: ./backend
      ports:
        - 5000:5000
      environment:
        - DB_HOST=data
        - DB_NAME=${DB_NAME?:}
        - DB_PORT=${DB_PORT?:}

/backend/Dockerfile /后端/Dockerfile

# pull official base image
FROM node:latest

# set working directory
WORKDIR /backend

EXPOSE 5000

ENV PORT=5000
ENV HOST=0.0.0.0

# install backend dependencies
COPY package*.json ./
RUN npm ci --only-production

# add backend
COPY . .

# start backend
CMD npm start

/backend/index.js /后端/index.js

const express = require("express")
const mongoose = require("mongoose")
const property = require("./routes/property-router")
const properties = require("./routes/properties-router")
const statistics = require("./routes/statistics-router")
const bodyParser = require("body-parser")
const dbConfig = require("./config/db.config")
require("dotenv").config();
var cors = require("cors")


// Connect to MongoDB database
mongoose
    .connect(dbConfig.url, { useNewUrlParser: true })
    .then(() => {
        const app = express()

        app.use(cors())

        app.use(bodyParser.text({ type: '*/*'}))

        app.use("/api", statistics)
        app.use("/api", properties)
        app.use("/api", property)

        const PORT = dbConfig.port || 5000;

        app.listen(PORT, () => {
            console.log(`Server is running on port ${PORT}.`);
        });
    })

/backend/config/db.config.js /backend/config/db.config.js

require('dotenv').config();

const {
    DB_HOST,
    DB_PORT,
    DB_NAME,
    PORT,
  } = process.env;
  
  module.exports = {
    url: `mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`,
    port: PORT
  };

/backend/.env /后端/.env

PORT=5000
HOST=localhost

DB_HOST=localhost
DB_NAME=propertyDB
DB_PORT=27017

Running the backend locally I can connect to the MongoDB Docker without any issues.在本地运行后端我可以毫无问题地连接到 MongoDB Docker。 By leaving only the data in the Docker Compose file and running node index.js.通过只保留 Docker Compose 文件中的数据并运行节点 index.js。

What am I doing wrong?我究竟做错了什么?

Edit编辑

I have even changed the URL from index.js to a random URL and still remains the same error and tries to connect to 127.0.0.1:27017.我什至将 URL 从 index.js 更改为随机 URL 并且仍然保持相同的错误并尝试连接到 127.0.0.1:27017。

.connect("randomurl.com", { useNewUrlParser: true })

The values in .env overwrite the environment variables in docker-compose.yml . docker-compose.yml中的值会覆盖.env中的环境变量。 Change改变

DB_HOST=localhost

to

DB_HOST=data

in .env ..env中。 The .env file should contain .env文件应包含

PORT=5000
HOST=localhost

DB_HOST=data
DB_NAME=propertyDB
DB_PORT=27017

Alternatively, you can remove (not copy) the .env file and set the values using environment variables.或者,您可以删除(而不是复制) .env文件并使用环境变量设置值。

Docker containers behave like nodes in a network. Docker 容器的行为类似于网络中的节点。

Unless you tell it not to, Docker Compose creates a virtual network, and assigns DNS names inside that network corresponding to the service names in the docker-compose.yml file.除非您告诉它不要这样做,否则 Docker Compose 会创建一个虚拟网络,并在该网络内分配与docker-compose.yml文件中的服务名称相对应的 DNS 名称。

The issue is that when you run the docker compose a new image is created and stored.问题是,当您运行 docker 组合时,会创建并存储一个新图像。 So every time you run the same container the same image will be executed.所以每次你运行同一个容器时,都会执行同一个镜像。 What you have to do is the following:您需要做的是:

For the first step, you should first shut down any running docker-compose configurations:第一步,您应该首先关闭所有正在运行的 docker-compose 配置:

$ docker-compose down

You can use the following command to verify that nothing is left running:您可以使用以下命令来验证是否没有任何东西在运行:

$ docker ps --all

To remove locally build images, first list all of the images cached locally, then remove anything that was built locally:要删除本地构建的图像,首先列出本地缓存的所有图像,然后删除本地构建的任何内容:

$ docker images

Then remove the image that is giving you issues.然后删除给您带来问题的图像。

$ docker rmi <image_name>

This solved the issue.这解决了这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongooseServerSelectionError:连接 ECONNREFUSED 127.0.0.1:27017 - MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 MongooseServerSelectionError:连接 ECONNREFUSED::1:27017 - MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 MongooseServerSelectionError:连接 ECONNREFUSED::1:27017 不会得到修复 - MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 wont get fixed MongooseServerSelectionError:连接 ECONNREFUSED 127.0.0.1:27017。 我已经尝试过 StackOverflow 中给出的所有解决方案,但它不起作用 - MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017. I have tried all solutions given in the StackOverflow, but its not working 节点app.js返回错误:连接ECONNREFUSED 127.0.0.1:27017 - Node app.js returns Error: connect ECONNREFUSED 127.0.0.1:27017 MongooseServerSelectionError:连接 ETIMEDOUT 13.250.154.115:27017 - MongooseServerSelectionError: connect ETIMEDOUT 13.250.154.115:27017 运行 supertest 时出现连接 ECONNREFUSED 127.0.0.1:80 错误 - Getting connect ECONNREFUSED 127.0.0.1:80 error when running supertest [SequelizeConnectionRefusedError]:连接ECONNREFUSED 127.0.0.1:3306 - [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:3306 AxiosError: 连接 ECONNREFUSED 127.0.0.1:80 - AxiosError: connect ECONNREFUSED 127.0.0.1:80 Microsoft Bot Emulator中的错误:连接ECONNREFUSED 127.0.0.1 - Error in Microsoft Bot Emulator: connect ECONNREFUSED 127.0.0.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM