如何在Dockerfile的RUN命令中用wget下载文件到指定路径并解决构建报错
问题描述
我的应用目录结构如下:
Root/ app.py requirements.txt imageHelpers/ helpers.py config.yml model.pth
我不想将model.pth复制到服务器,希望在构建Docker容器时从网络下载该文件,且下载后model.pth的路径必须为imageHelpers/model.pth。我使用的Dockerfile如下:
FROM python:3.9 WORKDIR /fast_api_test COPY ./requirements.txt /fast_api_test/requirements.txt RUN pip3 install -r /fast_api_test/requirements.txt COPY . . RUN python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' \ && wget -q -O /imageHelpers/model.pth https://MY_URL/model.pth EXPOSE 5000 CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "5000"]
我的运行环境为AWS + Ubuntu,执行sudo docker build -t fast_api .时出现如下报错:
/fast_api_test/imageHelpers/model.pth: No such file or directory The command '/bin/sh -c pip3 install --upgrade -r /fast_api_test/requirements.txt && python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' && wget -q -O /fast_api_test/imageHelpers/model.pth https://MY_URL/model.pth' returned a non-zero code: 1
请问wget -O PATH_TO_MODEL URL中的PATH_TO_MODEL应设为多少?
解决方案
错误根源:你指定的目标路径有误。Docker容器的工作目录已设为
/fast_api_test,执行COPY . .后,本地的imageHelpers目录会被复制到/fast_api_test下,因此正确的目标路径应该是/fast_api_test/imageHelpers/model.pth,而非你写的/imageHelpers/model.pth。另外,虽然COPY . .通常会创建imageHelpers目录,但为了避免本地目录缺失导致下载失败,建议先确保目录存在。正确的PATH_TO_MODEL:
有两种写法可选:- 绝对路径:
/fast_api_test/imageHelpers/model.pth - 相对路径(更简洁,基于当前工作目录):
./imageHelpers/model.pth
- 绝对路径:
修正后的Dockerfile关键片段:
用绝对路径的版本:
RUN python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' \ && mkdir -p /fast_api_test/imageHelpers \ && wget -q -O /fast_api_test/imageHelpers/model.pth https://MY_URL/model.pth
用相对路径的版本:
RUN python -m pip install 'git+https://github.com/facebookresearch/detectron2.git' \ && mkdir -p ./imageHelpers \ && wget -q -O ./imageHelpers/model.pth https://MY_URL/model.pth
- 补充说明:
mkdir -p命令会递归创建目录,即使上级目录不存在也能成功,确保下载路径有效。- 使用相对路径可以避免硬编码工作目录,让Dockerfile更易维护。
内容的提问来源于stack exchange,提问作者Deshwal
相关产品推荐
相关产品推荐

