2

I know that docker supports a .dockerignore file to exclude files for COPY commands. What I am looking for is opposite: a way to whitelist or copy files from a manifest.

One can create such a manifest by running:

git ls-files > files-to-include.txt

Does the Dockerfile syntax support such feature? Or is there another way to get the same result?

Jeffrey Mixon
  • 12,846
  • 4
  • 32
  • 55
link89
  • 1,064
  • 10
  • 13

1 Answers1

1

There is no built-in way to do this. However, with a little hacking you can create an "inverse dockerignore file" like this:

include.sh

#!/usr/bin/env sh

FILE=.dockerignore

# add git indexed files
git ls-files > $FILE
# add NOT symbol in front of each line to keep
sed -i 's/^/!/' $FILE
# add * as the first line in the file
sed -i '1s/^/*\n&/' $FILE

.dockerignore

The result is something like this:

*
!.dockerignore
!.gitignore
!Dockerfile
!LICENSE
!README.md
!bin/action.sh
!bin/commitlint
!commitlint-plugin-tense/blacklist.txt
!commitlint-plugin-tense/index.js
!commitlint-plugin-tense/index.test.js
!commitlint-plugin-tense/package-lock.json
!commitlint-plugin-tense/package.json
!commitlint.config.js
!package.json
!yarn.lock

Conclusion

The first line * ignores all files. Each subsequent line in the prefixed with ! tells Docker to NOT ignore the given file. The result is essentially a whitelist of files to add using COPY directive in a Dockerfile. The main thing to watch out for is that this file can quickly become obsolete when adding or removing files and would have to be constantly maintained.

Jeffrey Mixon
  • 12,846
  • 4
  • 32
  • 55
  • 2
    [`sed -i` has different syntax on Linux and macOS](https://stackoverflow.com/a/32005218/4265352). On Linux, the parameter of `-i` is optional and when it is not present, `sed` does not create a backup of the processed file. On macOS the parameter is required and in order to skip the backup one has to provide an empty string (`sed -i ''`). The file can be generated in one go like this: `(echo '*'; git ls-files | sed 's/^/!/') > .dockerignore` – axiac May 11 '23 at 08:58