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

使用Docker Compose安装FastAPI遇域名解析失败及版本匹配错误的解决方法

解决Docker构建FastAPI镜像时pip依赖安装失败问题

问题背景

尝试通过Docker Compose部署FastAPI+Angular项目,相关配置如下:

docker-compose.yml配置

version: "3.9"

services:
  fastapi_app:
    build:
      context: ./backend
    image: fastapi_app:latest
    ports:
      - target: 8000
        published: 8000
    volumes:
      - type: bind
        source: ./backend/app
        target: /app
    networks:
      - websocket

  angular:
    image: node:18.13.0-alpine
    working_dir: /frontend
    ports:
      - target: 4200
        published: 4200
    volumes:
      - type: bind
        source: ./frontend
        target: /frontend
    networks:
      - websocket
    command: npm start

networks:
  websocket:
    name: websocket
    driver: bridge

后端Dockerfile

FROM python:3.11
WORKDIR /app
COPY ./requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt
COPY ./app /app
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

requirements.txt内容

fastapi>=0.89.0
uvicorn[standard]>=0.20.0,<0.21.0

错误信息

构建镜像执行pip安装依赖时出现以下错误:

> [4/5] RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt:                                       
11.60 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7fb48a1ad890>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')': /simple/fastapi/                   

69.15 ERROR: Could not find a version that satisfies the requirement fastapi>=0.89.0 (from versions: none)
69.15 ERROR: No matching distribution found for fastapi>=0.89.0

解决方案

1. 修复Docker构建阶段的网络解析问题

错误提示里的Temporary failure in name resolution说明Docker容器在构建时无法解析PyPI域名,可通过两种方式修复:

方式A:给build阶段指定网络

修改docker-compose.yml中fastapi_app的build配置,添加网络参数,让构建过程使用已定义的websocket网络:

services:
  fastapi_app:
    build:
      context: ./backend
      network: websocket  # 添加该行配置
    # 其余配置保持不变

方式B:修改Docker全局DNS配置

编辑Docker守护进程配置文件(通常路径为/etc/docker/daemon.json),添加公共DNS服务器:

{
  "dns": ["8.8.8.8", "114.114.114.114"]
}

修改后重启Docker服务:

sudo systemctl restart docker

2. 切换国内PyPI镜像源加速安装

由于网络访问官方PyPI受限,可在pip命令中指定国内镜像源,修改Dockerfile中的RUN命令:

RUN pip install --no-cache-dir --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple -r /app/requirements.txt

常用国内镜像源还有阿里云https://mirrors.aliyun.com/pypi/simple/、豆瓣https://pypi.douban.com/simple/等。

3. 确认requirements.txt的合法性

检查依赖配置是否正确:

  • fastapi>=0.89.0为有效稳定版本,确认无拼写错误(如误写为fastpi)
  • uvicorn[standard]>=0.20.0,<0.21.0的版本范围合法,无需调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 18:10:39