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

使用docker-compose时Postgres拒绝其他容器连接问题求助

问题根因

Docker 同自定义网络内的容器互相通信时,需使用容器自身监听的内部端口,而非宿主机映射端口。你在 docker-compose.yml 中为 Postgres 配置的端口映射 5433:5432,仅作用于从宿主机或外部网络访问 Postgres 服务,容器内部 Postgres 始终监听默认的 5432 端口,你连接时错误使用了宿主机映射端口5433才导致连接被拒绝。

修复步骤

  1. 修改 index.ts 中的数据库连接配置,将 URL 中的端口从 5433 改为 5432:
const connection = await createConnection({
    type: 'postgres',
    // 端口改为容器内部的5432
    url: 'postgres://agoodusername:astrongpassword@db:5432/dbname',
    synchronize: false,
    entities: [Photo]
});
  1. 若使用 pgAdmin 连接 Postgres,也需填写端口为 5432 而非 5433。

可选优化(避免启动时序问题)

depends_on 仅控制容器启动顺序,不会等待 Postgres 完全初始化完成再启动后端服务,你当前的重试逻辑已经可以覆盖该场景,若想进一步简化逻辑,可以给 db 服务添加健康检查:

services:
  db:
    # 原有配置保留
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U agoodusername -d dbname"]
      interval: 5s
      timeout: 5s
      retries: 5
  be:
    # 原有配置保留
    depends_on:
      db:
        condition: service_healthy

内容的提问来源于stack exchange,提问作者Hamza Jadid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:57:03