.dockerignore versus .gitignore
In one line: Two files with the same syntax and different scope, plus patterns that keep the build context small and reproducible.
.dockerignore borrows most of its syntax from .gitignore: blank lines and # comments, ! re-includes, trailing slashes for directories, and **. What differs is the target.
Different scope
.gitignore removes files from version control. .dockerignore removes files from the build context that docker build sends to the daemon. So .git, .github and local settings files belong in it, while build outputs the image needs must not be dropped.
| Item | .gitignore | .dockerignore |
|---|---|---|
| Base | The directory holding the file | The build context root |
Leading / | Anchors to the repository root | No special meaning (root-relative anyway) |
! under an excluded directory | Void (git never descends) | Void (same trap) |
| Purpose | Control what is committed | Control payload size and cache invalidation |
A practical pattern
.git .gitignore node_modules npm-debug.log* Dockerfile .dockerignore *.md !README.md dist .env*
README.md returns through the !README.md rule. dist is a directory name pattern, so everything under it is dropped. .env* is a basic guard against baking secrets into an image.
Cache and order
Changing files in the context invalidates the COPY layer cache. Keeping logs and temporary files out of the context improves cache hits and shrinks the image. Do not drop lock files such as package-lock.json or pnpm-lock.yaml; reproducible builds depend on them.
Check the context
The “transferring context” size in the docker build output is a rough check. To inspect the exact set, list the patterns and paths in this debugger, or simulate with tar -cf - . | tar -tvf - after applying the rules.
Put the same rules and paths into the debugger to see the winning line and the traps immediately.
Open GlobLabFrequently asked questions
Are .dockerignore files still committed to git?
Yes. The files are independent: manage what the repository tracks and what the image build receives separately.
A re-included file keeps disappearing, why?
If a parent directory is excluded, a lower ! is void. Check the parent directory line in this debugger.
Sources
Read next
- .gitignore order, re-includes, and the excluded-parent trapLast match wins, why a `!` re-include stops working under an excluded directory, and safer exception patterns, with examples.
- Pattern syntax: .gitignore versus GitHub Actions pathsHow `**`, `*`, `?` and `[]` differ between the two systems, and why paths and paths-ignore cannot be combined.
- The rsync include/exclude first-match trapRule order in rsync, directory pruning, and a filter order that survives backups, with broken and fixed examples.