Search code examples
dockerdockerignore

.dockerignore pattern to exclude files in all subdirectories


How can I exclude python generated files like *.pyc in all subdirectories from the docker image?

I added .dockerignore at the root of the context directory:

# Ignore generated files
*.pyc

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

/contextdir/
|-- Dockerfile
\-- src/
    |-- a.py   # this is copied - all right
    \-- a.pyc  # this should be ignored, but is copied too. Why?

Solution

  • 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
    **/*.pyc
    

    The reference at How to create a dockerignore file doesn't put that clear enough.

    Finally, I understood that 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?