首页 > 解决方案 > Docker - 使 ADD 命令以命令行参数为条件

问题描述

可以ADD自定义命令以使用命令行参数。基本上我有不同版本的文件,比如说file1和file2,并且基于通过命令行传递的某些条件。

以下命令正常工作并将file从主机传输到 docker,但我没有找到任何有条件地执行此操作的参考。
ADD target/file.yml file.yml

标签: docker

解决方案


不,ADD不支持复制文件的条件方式。

但是有一种方法可以在从 Host 应对时处理此类配置。

  • 在您的情况下将所有配置复制到某个临时位置,将所有配置复制file1 file2到某个/temp位置,然后基于ARG传递给 docker build,filetarget.
  • 或者使用基于 的 docker 入口点执行上述操作ENV,而不是基于ARG
FROM alpine
ADD target/ /temp_target
RUN mkdir /target

#filename to be copied to the target 
ARG file_name

# pass update_file true or false if true file wil be update to new that is passed to build-args
ARG update_file

ENV file_name=$file_name
ARG update_file=$update_file

#check if update_file is set and its value is true then copy the file from temp to target, else copy file1 to target
RUN if [ ! -z "$update_file" ] && [ "${update_file}" == true ];then \
   echo "$update_file"; \
   echo "echo file in temp_target"; \
   ls /temp_target ;\
   echo "updating file target" ;\
   cp /temp_target/"${file_name}" /target/ ; \
   echo "list of updated files in target"; \
   ls /target ; \
   else \
   echo "copy with default file that is ${file_name}" ;\
   cp /temp_target/file1 /target ;\
   fi

建造:

这不会更新文件,将使用默认文件名 file1 进行复制

docker build --no-cache --build-arg file_name=file1 --build-arg update_file=false -t abc .

这将更新目标中的文件,因此目标中的新文件是file2。

 docker build --no-cache --build-arg file_name=file2 --build-arg update_file=true -t abc .

推荐阅读