【问题标题】:Getting a "ECONNREFUSED 0.0.0.0:5432" connection error on Docker Compose在 Docker Compose 上出现“ECONNREFUSED 0.0.0.0:5432”连接错误
【发布时间】:2021-05-07 06:38:41
【问题描述】:

我有一个 Docker compose YML 文件,其中定义了 2 个容器,当我运行 Docker compose 时,我收到“ECONNREFUSED 0.0.0.0:5432”错误。

查看错误日志,数据库服务器(Postgres)容器正在运行并准备好传入连接,但是当应用程序(Node js app)容器时

奇怪的是它们在同一个网络上,并且在两个容器上“0.0.0.0:5432”端口已设置并公开,但是当应用程序容器进行数据库调用时它们仍然没有连接(见下图)

Docker 撰写:

version: "3.3"

services:

    # container 1
    application:
        ports:
            - "8000:8000"
        build:
            context: .
            dockerfile: ./dockerfile-app
        volumes:
            - .:/docker-app
        depends_on:
            database:
                condition: service_healthy
        restart: 
            always
        networks:
            - one_network

    # container 2
    database:
        image:
            postgres:12.6
        ports:
            - "5432:5432"
        volumes:
            - ./postgres-data:/var/lib/postgresql/data
        healthcheck:
            test: ["CMD-SHELL", "pg_isready -U postgres"]
            interval: 5s
            timeout: 5s
            retries: 5
        environment:
            POSTGRES_DB: "postgres"
            POSTGRES_USER: "postgres"
            POSTGRES_PASSWORD: "postgres"
        restart: 
            always
        networks:
            - one_network

networks:
    one_network:

Dockerfile:

# Base image
FROM ubuntu:16.04

# System updates
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt -y install -y software-properties-common curl

# Install Nodejs
RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - && apt install -y nodejs

# Copy bash file for post-build tasks
WORKDIR /docker-app
COPY /docker-app.sh .

# Install Node packages
COPY /package.json .
RUN echo $PWD
RUN npm install

# Runs post-build commands
CMD ["sh", "./docker-app.sh"]

谁能帮我理解为什么会出现这个错误?

【问题讨论】:

  • 也许这不是您问题的根源,但您为什么要从ubuntu 构建node 图像?
  • 这是您用来与数据库对话的 url。它不在 0.0.0.0:5432 上,它在 database:5432 上
  • 0.0.0.0 是一个特殊的 IPv4 地址,意思是“无处不在”。通常,服务器会侦听 0.0.0.0,但将其用作数据库主机名或 URL 是没有意义的。

标签: docker docker-compose containers


【解决方案1】:

所以我设法解决了这个问题......这与 Docker 无关,而是在我的 Node js 应用程序配置中:

module.exports = {
  client: 'pg',
  connection: {
    // host is the same name as the Docker container DB service
    host: 'database',
    port: '5432',
    user: 'postgres',
    password: 'postgres',
    database: 'postgres'
  },

注意:'host' 变量,它不是 localhost 或 127.0.0.1 或类似的东西。而是运行数据库的容器的名称(上面在我的 Docker Compose 文件中命名)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 2022-06-28
    • 2022-12-21
    • 2021-02-17
    • 2019-10-08
    • 2019-09-08
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多