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

Docker-Compose部署时psycopg2连接PostgreSQL遭拒绝求助

问题:PostgreSQL容器与Python应用容器连接失败,错误提示Connection refused

我的配置文件

docker-compose.yml

version: '3'
services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: example
      POSTGRES_DB: mydatabase
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
  app:
    build: .
    depends_on:
      - db
    environment:
      DATABASE_URL: postgresql://postgres:example@db:5432/mydatabase

Dockerfile

FROM python:3.8    
WORKDIR /app    
COPY requirements.txt .    
RUN pip install -r requirements.txt    
COPY . .    
CMD ["python", "./app.py"]

app.py 关键代码

conn = psycopg2.connect(
    host="db",
    database="mydatabase",
    user="postgres",
    password="example",
    port="5432"
)

cur = conn.cursor()
cur.execute("SELECT version();")
print(cur.fetchone())

问题现象

执行docker-compose up --build后,应用抛出错误:

psycopg2.OperationalError: connection to server at "db" (172.20.0.3), port 5432 failed: Connection refused

连接失败的核心原因
  • depends_on仅保证容器启动顺序,不保证服务就绪:docker-compose的depends_on只是让app容器在db容器之后启动,但PostgreSQL容器启动后需要时间完成初始化(比如创建指定数据库、执行挂载的init.sql脚本),此时app已经开始发起连接请求,自然会被拒绝。
  • 应用缺少等待数据库就绪的逻辑:你的Python应用启动后直接尝试连接数据库,没有检测数据库服务是否完全可用的步骤,大概率赶在PostgreSQL初始化完成前发起请求。
  • 初始化脚本可能拖慢服务就绪:如果./init.sql包含大量数据插入或复杂SQL操作,数据库会在脚本执行完毕后才对外提供服务,这段时间内应用的连接请求都会失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:34:50