Search code examples
docker

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


I used to list the tests directory in .dockerignore so that it wouldn't get included in the image, which I used to run a web service.

Now I'm trying to use Docker to run my unit tests, and in this case I want the tests directory included.

I've checked docker build -h and found no option related.

How can I do this?


Solution

  • 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 comment0, comment1, comment2


    from Mugen comment, please note

    the custom dockerignore should be in the same directory as the Dockerfile and not in root context directory like the original .dockerignore

    i.e.

    when calling

    DOCKER_BUILDKIT=1
    docker build -f /path/to/custom.Dockerfile ...

    your .dockerignore file should be at

    /path/to/custom.Dockerfile.dockerignore