【问题标题】:is it possible to allow failure in COPY at a Dockerfile?是否可以在 Dockerfile 中允许 COPY 失败?
【发布时间】:2021-11-24 13:20:21
【问题描述】:

我有一个这样的多级 Docker 文件:

From A as a
WORKDIR /app
COPY . .

From B as b
COPY --from=a /app/path/to/a/file /destination/file/path

有时最后一个COPY 的源文件不存在,这会导致docker build 失败。不用担心/app/path/to/a/file 的存在就可以施展魔法吗?

【问题讨论】:

    标签: docker dockerfile docker-multi-stage-build


    【解决方案1】:

    我认为没有办法允许 COPY 指令失败,但您可以做的不是复制特定文件,而是复制确实存在的文件夹的内容(即使它是空的)。

    例如,假设您有这样的文件夹结构

    .
    ├── Dockerfile
    └── test_folder
        └── test_file
    
    1 directory, 2 files
    

    然后你从这个 Dockerfile 构建:

    FROM alpine as alp1
    WORKDIR /app
    COPY . .
    
    FROM alpine
    RUN mkdir /dest_folder
    COPY --from=alp1 /app/test_folder/test_file /dest_folder
    

    如果因为文件确实存在而有效,并且如果我们要从该文件夹中删除该文件,则 COPY 将失败。

    因此,我们可以复制/app/test_folder/,而不是复制/app/test_folder/test_file,这会将test_folder中的所有内容复制到第二个容器中的/dest_folder,即使没有任何内容:

    文件已删除:

    .
    ├── Dockerfile
    └── test_folder
    
    1 directory, 1 file
    

    构建自:

    FROM alpine as alp1
    WORKDIR /app
    COPY . .
    
    FROM alpine
    RUN mkdir /dest_folder
    COPY --from=alp1 /app/test_folder/ /dest_folder
    
    > docker build -t test .
    
    Sending build context to Docker daemon   2.56kB
    Step 1/6 : FROM alpine as alp1
     ---> 0a97eee8041e
    Step 2/6 : WORKDIR /app
     ---> Using cache
     ---> 0a6fc3a90e15
    Step 3/6 : COPY . .
     ---> Using cache
     ---> 076efaa3a8b9
    Step 4/6 : FROM alpine
     ---> 0a97eee8041e
    Step 5/6 : RUN mkdir /dest_folder
     ---> Using cache
     ---> 8d647b9a1573
    Step 6/6 : COPY --from=alp1 /app/test_folder/ /dest_folder
     ---> Using cache
     ---> 361b0919c585
    Successfully built 361b0919c585
    Successfully tagged test:latest
    

    dest_folder 存在:

    docker run -it --rm test ls
    bin          etc          media        proc         sbin         tmp
    dest_folder  home         mnt          root         srv          usr
    dev          lib          opt          run          sys          var
    

    里面什么都没有

    docker run -it --rm test ls -lah /dest_folder
    total 8K
    drwxr-xr-x    1 root     root        4.0K Nov 24 14:06 .
    drwxr-xr-x    1 root     root        4.0K Nov 24 14:13 ..
    

    【讨论】:

    • 感谢您的回答。我曾考虑过这个解决方案,但我想将(在你的示例中)test_file 内容复制到dest_file,如果有诸如test_file2 之类的目录,则该文件的内容应该复制到dest_file
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2020-12-09
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多