7

I have a repository that I would like to build an image for. There are multiple folders in there and I would like to exclude one called 'solver'. Using a dockerignore file is not an option.

I have tried:

COPY ./[(^solver)] ./
COPY ./[(^solver)]* ./
COPY ./[^solver] ./

However these are not working.

The second solution in this post does not solve my problem.

hojkoff
  • 185
  • 1
  • 8

1 Answers1

1

As long as .dockerignore is not an option, there are 3 methods that will work:

  1. Exclude the folder from COPY by multiple copy instructions (one for each letter):

     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'
    

    Disadvantage: This will flatten the folders structures, also, imagine that you have more than one folder to do that for :(

    Note, the requirement for file_that_always_exists.txt (e.g. can be Dockerfile) is to avoid the error COPY failed: no source files were specified if there are no files that match the copy step.

  2. Copy all folders and then in a different layer delete the unwanted folder:

     COPY . .
     RUN rm -rf ./solver
    

    Disadvantage: The content of the folder will still be visible in the Docker image, and if you are trying to decrease the image size this will not help.

  3. Manually specify the files and folders you would like to copy ():

     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/
    

    Disadvantage: You have to manually write all files and folders, but more annoyingly, manually update the list when the folder hierarchy changes.

Each method has it's own advantages and disadvantages, choose the one that most fit your application requirements.

Yogev Neumann
  • 2,099
  • 2
  • 13
  • 24
  • regarding #2, when you say "content of the folder will still be visible in the Docker image", do you mean it is visible for the fraction of a second before the `RUN rm -rf ./solver` runs ? – k1eran Jun 15 '23 at 16:19
  • 1
    @k1eran I meant that it will be in a [different layer](https://stackoverflow.com/questions/56885945/dockerfile-copy-and-run-in-one-layer), so whoever inspect the image can see it and you don't save up space – Yogev Neumann Jun 16 '23 at 01:51