How to specify different .dockerignore files for different builds in the same project?

Docker 19.03 shipped a solution for this.

The Docker client tries to load <dockerfile-name>.dockerignore first and then falls back to .dockerignore if it can't be found. So docker build -f Dockerfile.foo . first tries to load Dockerfile.foo.dockerignore.

Setting the DOCKER_BUILDKIT=1 environment variable is currently required to use this feature. This flag can be used with docker compose since 1.25.0-rc3 by also specifying COMPOSE_DOCKER_CLI_BUILD=1.

See also:

  • https://github.com/moby/moby/issues/12886#issuecomment-480575928
  • https://github.com/moby/moby/issues/12886#issuecomment-518843764
  • https://github.com/moby/moby/issues/12886#issuecomment-523706042

At the moment, there is no way to do this. There is a lengthy discussion about adding an --ignore flag to Docker to provide the ignore file to use - please see here.

The options you have at the moment are mostly ugly:

  • Split your project into subdirectories that each have their own Dockerfile and .dockerignore, which might not work in your case.
  • Create a script that copies the relevant files into a temporary directory and run the Docker build there.

Adding the cleaned tests as a volume mount to the container could be an option here. After you build the image, if running it for testing, mount the source code containing the tests on top of the cleaned up code.

services:
   tests:
      image: my-clean-image
      volumes:
         - '../app:/opt/app' # Add removed tests

Tags:

Docker