Search code examples
dockershellnode-modulesdockerignore

How to test dockerignore file?


After reading the .dockerignore documentation, I'm wondering if there is a way to test it?

Examples

**/node_modules/

How do I check my dockerfile ignore the correct files and directories?


Solution

  • One thing that the other answers do not consider, is that this will potentially copy many gigabytes of data and be very slow, when all you want to do is find out which file(s) you need to exclude to reduce the image size.

    So here is how you test your .dockerignore without actually copying data:

    $ rsync -avn . /dev/shm --exclude-from .dockerignore
    

    What this will do, is try to sync your current directory with the empty in-memory folder /dev/shm verbosely and dry-run (don't actually copy anything) the --exclude-from option reads glob patterns in the same format as .gitignore and .dockerignore

    You will end up with a list of files copied and a summary with the total size at the end:

    file.bogus
    tests/
    tests/conftest.py
    tests/test_model.py
    
    sent 1,954 bytes  received 207 bytes  4,322.00 bytes/sec
    total size is 209,916,337  speedup is 97,138.52 (DRY RUN)
    

    Add it to .dockerignore:

    *.bogus
    

    and test again:

    tests/
    tests/conftest.py
    tests/test_model.py
    
    sent 1,925 bytes  received 204 bytes  4,258.00 bytes/sec
    total size is 201,145  speedup is 94.48 (DRY RUN)
    

    This is extremely fast and doesn't fill your disk.

    Edit: There is one difference that I have found. For rsync the pattern *.bogus matches all files with that name regardless of the directory. .dockerignore however only matches *.bogus in the current directory. To get the same behavior you need to prefix the pattern with the path glob characters **/*.bogus This will still work with rsync.