从不带 .dockerignore 的 docker build COPY 命令中排除文件夹

hoj*_*off 7 docker dockerfile

我有一个存储库,我想为其构建图像。那里有多个文件夹,我想排除一个名为“solver”的文件夹。使用 dockerignore 文件不是一个选项。

我努力了:

COPY ./[(^solver)] ./
COPY ./[(^solver)]* ./
COPY ./[^solver] ./
Run Code Online (Sandbox Code Playgroud)

然而这些都不起作用。

这篇文章中的第二个解决方案并没有解决我的问题。

Yog*_*ann 1

只要.dockerignore不是一个选项,就有 3 种方法可以使用:

  1. 通过多个复制指令排除文件夹COPY(每个字母一个):

     COPY ./file_that_always_exists.txt ./[^s]* .        # All files that don't start with 's'
     COPY ./file_that_always_exists.txt ./s[^o]* .       # All files that start with 's', but not 'so'
     COPY ./file_that_always_exists.txt ./so[^l]* .      # All files that start with 'so', but not 'sol'
     COPY ./file_that_always_exists.txt ./sol[^v]* .     # All files that start with 'sol', but not 'solv'
     COPY ./file_that_always_exists.txt ./solv[^e]* .    # All files that start with 'solv', but not 'solve'
     COPY ./file_that_always_exists.txt ./solve[^r]* .   # All files that start with 'solve', but not 'solver'
    
    Run Code Online (Sandbox Code Playgroud)

    缺点:这会使文件夹结构变平,此外,想象一下您有多个文件夹可以执行此操作:(

    file_that_always_exists.txt请注意, (例如可以是)的要求是为了避免在没有与复制步骤匹配的文件时出现Dockerfile错误。COPY failed: no source files were specified

  2. 复制所有文件夹,然后在不同的层中删除不需要的文件夹:

     COPY . .
     RUN rm -rf ./solver
    
    Run Code Online (Sandbox Code Playgroud)

    缺点:文件夹的内容在 Docker 映像中仍然可见,如果您尝试减小映像大小,这将无济于事。

  3. 手动指定您要复制的文件和文件夹 ():

     COPY ["./file_to_copy_1.ext", "file_to_copy_2.ext", "file_to_copy_3.ext", "."]
     COPY ./folder_to_copy_1/ ./folder_to_copy_1/
     # ...
     COPY ./folder_to_copy_n/ ./folder_to_copy_n/
    
    Run Code Online (Sandbox Code Playgroud)

    缺点:你必须手动写入所有文件和文件夹,但更烦人的是,当文件夹层次结构发生变化时,需要手动更新列表。

每种方法都有其自身的优点和缺点,请选择最适合您的应用要求的一种。