Docker ignores patterns in .dockerignore

I intended to exclude python generated files from the docker image. So I added .dockerignore at the root of the context directory:

# Ignore generated files

Alas docker build ignores this and copies the entire directory tree that looks like the following:

  • How does Docker share resources
  • how to setup dns nameserver in docker permanently in user-defined network?
  • Enable CORS on Cloudant local
  • running a webpack watch process in a separate docker container
  • Wrong time in Docker container of Django app built by Jenkins
  • Volume sharing in Docker and Virtualbox
  • /contextdir/
    |-- Dockerfile
    \-- src/
        |--   # this is copies - all right
        \-- a.pyc  # this should be ignored, but is copied too. Why?

  • Connection issue with Jenkins within Docker on RaspberryPi 3 (rpi-jenkins) when cloning a Bitbucket Git Repo
  • Issue staring docker container with nginx and passenger
  • How to check if docker daemon is running?
  • Access logs of a killed docker container
  • Saving docker credentials in docker config
  • kubernetes stateful set connection
  • 2 Solutions collect form web for “Docker ignores patterns in .dockerignore”

    Finally, I understood what’s the trick. For some reason, I wasn’t able to find any mention of this and haven’t found any example Dockerfile with such construct, so documenting it here. Was it trivial for everybody else?

    The reference at doesn’t put clear enough that patterns like *.pyc are matched only at the beginning of the path, or for the files directly below the context directory, but not recursively. To make it work recursively the **/ syntax must be used:

    # Ignore generated files

    The docs for .dockerignore state that the pattern matching use’s Go’s filepath matching logic. The docs also cover the recursive pattern:

    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.

    Docker will be the best open platform for developers and sysadmins to build, ship, and run distributed applications.