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

Docker部署FastAPI应用无法连接容器化PostgreSQL数据库问题

容器化FastAPI无法连接同环境PostgreSQL数据库

问题核心

你的FastAPI应用容器尝试连接localhost:5432,但在Docker Compose默认网络中,每个容器的localhost仅指向自身,而非PostgreSQL容器。这就是本地运行应用能正常连接(此时localhost指向宿主机,数据库端口已映射到宿主机),但容器化后连接失败的原因。

解决方案

修改.env文件中的数据库连接地址,将localhost替换为Docker Compose里数据库服务的名称database。

比如原数据库URL:

DATABASE_URL=postgresql://user:password@localhost:5432/dbname

修改为:

DATABASE_URL=postgresql://user:password@database:5432/dbname

额外注意事项

  • depends_on的局限性:depends_on仅保证app容器在database容器之后启动,但不确保PostgreSQL服务完全就绪。若数据库启动较慢,应用可能仍会连接失败,可添加启动延迟,或用wait-for-it这类工具等待数据库端口开放后再启动应用。
  • 网络特性:Docker Compose会自动为所有服务创建默认网络,服务名称可直接作为域名解析到对应容器的IP,无需额外配置端口映射(除非需要从宿主机访问数据库)。

报错信息

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

配置文件参考

Dockerfile

FROM python:3.9

ENV PYTHONPATH "${PYTHONPATH}:/"
ENV PORT=8000

RUN pip install --upgrade pip

COPY ./requirements.txt .

RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY ./app /app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

docker-compose.yml

version: "3.8"

services:
  app:
    build: .
    env_file:
      - .env
    ports:
      - "8000:8000"
    depends_on:
      - database


  database:
    image: postgres:12
    env_file:
      - .env
    ports:
      - "5432:5432"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:05:33