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

Docker Compose构建时无法找到构建上下文内文件的排查求助

Docker构建文件读取失败排查求助

错误信息

ERROR [4/5] RUN cat ./test.txt                                                                                                                                                                    
0.2s
------
> [4/5] RUN cat ./test.txt:
#0 0.225 cat: ./test.txt: No such file or directory
------
failed to solve: process "/bin/sh -c cat ./test.txt" did not complete successfully:  
exit code: 1

已尝试的解决方案

  • 将文件权限修改为777
  • 反复确认文件确实位于构建上下文目录内
  • 检查文件所有权(状态正常)
  • 确认test.txt不是隐藏文件
  • 检查.dockerignore是否忽略了该文件
  • 使用--no-cache参数重新构建,无变化

Docker Compose配置文件

fortune_teller_worker:
  build:
    context: /home/lds/apps/fortuneteller/Docker/Cron  
    dockerfile: DockerfileCron             
  restart: always
  container_name: ft_worker
  volumes:
    - /home/lds/apps/fortuneteller:/app
  working_dir: /app
  networks:
    - my_app_net
  command: bash -c "service cron start && pip install -r requirements.txt && tail -f /dev/null"

DockerfileCron(注:<<仅用于标记尝试过的操作,实际未包含)

FROM python:3

RUN apt-get update && \
    apt-get install -y cron vim && \
    pip install --upgrade pip

# 以下为尝试过的无效命令
# RUN cat ./test.txt
# RUN cat test.txt
# RUN cat /test.txt

# 在RUN cat前后都尝试过设置WORKDIR,无变化
# WORKDIR /app

CMD ["cron", "-f"]

目录结构

builder/
└── docker-compose.yml

app/
└── Docker/
    └── Cron/
        ├── DockerfileCron
        └── test.txt

问题概述

执行RUN cat test.txt仅用于测试是否能读取构建上下文内的文件,但始终提示文件不存在,已尝试多种常规排查方法无效,求其他可行的排查方向。


补充排查方案

  1. 添加文件复制步骤到Dockerfile:构建上下文的文件不会自动进入镜像,必须通过COPY或ADD命令复制到镜像内。在RUN cat之前添加:
    COPY test.txt .
    
    再执行构建,这是最可能的问题根源——你没把test.txt复制到镜像构建环境中。
  2. 打印当前目录内容验证:在RUN cat命令前添加RUN ls -la,查看构建时当前目录下的所有文件,确认test.txt是否真的存在。
  3. 跳过Docker Compose直接构建:进入/home/lds/apps/fortuneteller/Docker/Cron目录,执行:
    docker build -t test-image .
    
    若直接构建成功,说明问题出在Docker Compose的配置上。
  4. 修改Docker Compose的context路径为相对路径:假设docker-compose.yml在builder目录,将context改为:
    context: ../app/Docker/Cron
    
    避免绝对路径可能带来的权限或路径解析问题。
  5. 验证构建上下文传递范围:从builder目录执行手动构建命令,确认上下文传递是否正常:
    docker build -f ../app/Docker/Cron/DockerfileCron ../app/Docker/Cron
    
  6. 检查构建时的用户权限:在Dockerfile中添加RUN whoami,查看构建过程使用的用户是否有文件读取权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:13:26