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

执行docker-compose build时复制requirements.txt至容器出错求助

问题:执行docker-compose build时无法找到requirements.txt

错误信息

=> ERROR [3/5] COPY ../requirements.txt /code/
failed to compute cache key: "/requirements.txt" not found: not found
ERROR: Service 'web' failed to build : Build failed

目录结构

.
├── backend/
│   └── api/
│       ├── __init__.py
│       ├── main.py
│       └── Dockerfile
├── .dockerignore
├── docker-compose.yml
└── requirements.txt

相关文件内容

backend/api/Dockerfile

FROM python:3.10.8-slim-buster

WORKDIR /code

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

COPY ../requirements.txt /code/

RUN pip3 install --no-cache-dir --upgrade -r /code/requirements.txt

COPY ./api /code/api

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

根目录docker-compose.yml

version: "3.8"

services:
  web:
    container_name: "sukeba_api"
    build: ./backend
    volumes:
      - ./backend/api:/code/api
    ports:
      - "8000:80"
    depends_on:
      - db
  db:
    image: postgres:latest
    container_name: "sukeba_db"
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    ports:
      - 5432:5432
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=sukeba

volumes:
  postgres_data:

解决方案

问题核心是Docker构建上下文范围和COPY路径不匹配:

  • 调整docker-compose.yml的构建配置
    当前build: ./backend把构建上下文限制在了backend目录,而requirements.txt在根目录,Docker无法访问上下文外的文件。修改build字段,将上下文设为根目录,同时指定Dockerfile的具体路径:

    web:
      # 保留其他配置不变
      build:
        context: .
        dockerfile: ./backend/api/Dockerfile
    
  • 修改Dockerfile中的COPY路径
    构建上下文改为根目录后,直接使用根目录下的requirements.txt路径即可,无需../:

    COPY requirements.txt /code/
    
  • 可选方案(调整目录结构)
    若不想修改配置,可将requirements.txt移动到backend目录下,同时修改Dockerfile的COPY指令为COPY ./requirements.txt /code/,但前一种方案更能保持根目录配置文件的结构清晰。

完成修改后,重新执行docker-compose build即可正常构建。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:51:36