You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose中Node服务连接Postgres报ECONNREFUSED错误如何解决

问题解决方案

根本原因

Docker Compose 会为所有服务创建独立的内部网络,每个容器的 localhost 仅指向容器自身的环回地址,无法访问其他服务的端口。你当前 Express 配置中数据库 host 填的是 localhost,会请求 app 容器自身的 5432 端口,而 postgres 服务运行在独立的 postgres_db 容器中,因此连接被拒绝。

修复步骤

  1. 修改Express数据库连接配置
    将配置中的 host 字段从 localhost 改为 postgres 服务在 docker-compose 中定义的服务名 postgres_db,Docker Compose 内置的DNS会自动解析服务名到对应容器的内部IP:
module.exports = {
    user: 'postgres',
    host: 'postgres_db', // 替换原localhost
    database: 'postgres',
    password: 'postgres',
    port: 5432,
}
  1. (推荐)兼容本地开发与容器部署的优化方案
    不要硬编码配置值,改为读取环境变量,适配不同运行环境:
  • 在docker-compose.yml的app服务中新增环境变量配置:
app:
    image: node
    build: ./API/
    restart: always
    volumes:
      - .:/app/
      - /app/node_modules
    ports:
      - "3001:3001"
    depends_on:
      - postgres_db
    # 新增以下环境变量
    environment:
      - DB_HOST=postgres_db
      - DB_USER=postgres
      - DB_PASSWORD=postgres
      - DB_NAME=postgres
      - DB_PORT=5432
  • 修改Express数据库配置,优先读取环境变量,本地开发时自动降级为默认值:
module.exports = {
    user: process.env.DB_USER || 'postgres',
    host: process.env.DB_HOST || 'localhost',
    database: process.env.DB_NAME || 'postgres',
    password: process.env.DB_PASSWORD || 'postgres',
    port: process.env.DB_PORT || 5432,
}
  1. 可选:解决服务启动时序问题
    depends_on 仅保证容器启动顺序,不会等待postgres服务完全初始化就绪,若偶发连接失败可添加健康检查配置:
  • 给postgres_db服务增加健康检查:
postgres_db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - "5432:5432"
    # 新增健康检查
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
  • 修改app服务的depends_on配置,等待postgres健康检查通过后再启动:
depends_on:
      postgres_db:
        condition: service_healthy

内容的提问来源于stack exchange,提问作者Turqay Umudzade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:45:04