在 Docker Compose 上出现“ECONNREFUSED 0.0.0.0:5432”连接错误

问题描述 投票:0回答:2

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

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

奇怪的是,它们位于同一网络上,并且在两个容器上都已设置并公开“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"]

任何人都可以帮助我理解为什么我会收到此错误吗?

docker docker-compose containers
2个回答
4
投票

所以我设法解决了这个问题...这与 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 文件中指定)


0
投票

您可能已经使用 Docker Desktop 搜索 postgres 来运行此程序?

如果是这样,它们的端口绑定不正确。

我将使用正确的绑定手动运行

docker run
命令,如下所示:

docker run --name postgres -e POSTGRES_PASSWORD=password -d -p 5432:5432 postgres

这样您就可以使用

localhost:5432

正确连接到主机上的容器
© www.soinside.com 2019 - 2024. All rights reserved.