Dockerignore: Ignore everything except a file and the Dockerfile

If you need to ignore everything except some directories or files and also ignore some unnecessary files inside those allowed directories you can use the following .dockerignore file:

# Ignore everything
**

# Allow files and directories
!/file.txt
!/src/**

# Ignore unnecessary files inside allowed directories
# This should go after the allowed directories
**/*~
**/*.log
**/.DS_Store
**/Thumbs.db

From the dockerfile reference:

Beyond Go’s filepath.Match rules, Docker also supports a special wildcard string ** that matches any number of directories (including zero). For example, **/*.go will exclude all files that end with .go that are found in all directories, including the root of the build context.

So a line containing simply ** will ignore everything in the same directory as the Dockerfile.

As expected the exclamation can then be used to reference any files you do wish to send to the docker daemon.