Dockerfile中的条件复制/添加?

新手上路,请多包涵

在我的 Dockerfiles 中,如果存在,我想将一个文件复制到我的图像中,pip 的 requirements.txt 文件似乎是一个不错的候选者,但是如何实现呢?

 COPY (requirements.txt if test -e requirements.txt; fi) /destination
...
RUN  if test -e requirements.txt; then pip install -r requirements.txt; fi

或者

if test -e requirements.txt; then
    COPY requiements.txt /destination;
fi
RUN  if test -e requirements.txt; then pip install -r requirements.txt; fi

原文由 derrend 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

目前不支持此功能(因为我怀疑它会导致无法复制的图像,因为相同的 Dockerfile 会复制或不复制该文件,具体取决于它的存在)。

issue 13045 中仍然要求使用通配符:“ COPY foo/* bar/" not work if no file in foo ”(2015 年 5 月)。

它现在(2015 年 7 月)不会在 Docker 中实现,但是像 bocker 这样的另一个构建工具可以支持这一点。


2021 年

COPY source/. /source/ 对我有用(即在为空时复制目录,如“ 无论是否为空,都将目录复制到 docker build - 失败” COPY failed: no source files were specified ”)

2022

这是我的建议:

 # syntax=docker/dockerfile:1.2

RUN --mount=type=bind,source=jars,target=/build/jars \
 find /build/jars -type f -name '*.jar' -maxdepth 1  -print0 \
 | xargs -0 --no-run-if-empty --replace=source cp --force source >"${INSTALL_PATH}/modules/"

这可以解决:

 COPY jars/*.jar "${INSTALL_PATH}/modules/"

但是如果没有找到,则复制 no *.jar ,不会引发错误。

原文由 VonC 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是一个简单的解决方法:

 COPY foo file-which-may-exist* /target

确保 foo 存在,因为 COPY 至少需要一个有效来源。

如果 file-which-may-exist 存在,它也会被复制。

注意:您应该注意确保您的通配符不会选择您不打算复制的其他文件。为了更加小心,您可以使用 file-which-may-exist? 代替( ? 只匹配一个字符)。

或者更好的是,使用这样的字符类来确保只能匹配一个文件:

 COPY foo file-which-may-exis[t] /target

原文由 jdhildeb 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题