0

I have a multistage Docker file like this:

From A as a
WORKDIR /app
COPY . .

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

Sometimes the source-file of last COPY does not exist and this causes a failure in docker build. Is it possbile to do the magic w/o worrying about the existence of /app/path/to/a/file?

iLuvLogix
  • 5,920
  • 3
  • 26
  • 43

1 Answers1

2

I don't suppose there is a way to allow for a failure in a COPY instruction, but what you could do is copy not a specific file, but the content of the folder that does exist (even if it's empty).

For example, imagine you have a folder structure like this

.
├── Dockerfile
└── test_folder
    └── test_file

1 directory, 2 files

and you build from this Dockerfile:

FROM alpine as alp1
WORKDIR /app
COPY . .

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

if works because the file does exist and if we were to delete the file from that folder, the COPY would fail.

So instead of copying /app/test_folder/test_file we could copy /app/test_folder/, which will copy EVERYTHING from inside the test_folder to /dest_folder in the second container, EVEN if there is nothing:

file removed:

.
├── Dockerfile
└── test_folder

1 directory, 1 file

building from:

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 exists:

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

but nothing is inside

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 ..
jabbson
  • 4,390
  • 1
  • 13
  • 23
  • thanks for your answer. i had think to this solution, but i want to copy (in your example) `test_file` contents to the `dest_file` and if there was a dir such as `test_file2`, the contents of that file should copy to `dest_file`. – mohammad hosein bahmani Nov 28 '21 at 08:44