opyebGlobLab

.dockerignore versus .gitignore

Docker · 5 min read

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
BaseThe directory holding the fileThe build context root
Leading /Anchors to the repository rootNo special meaning (root-relative anyway)
! under an excluded directoryVoid (git never descends)Void (same trap)
PurposeControl what is committedControl 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 GlobLab

Frequently 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

0 bytes of your input sent to a server (advertising and affiliate widgets excluded)