.dockerignore
A .dockerignore file is a text file in the build context root that lists paths Docker must leave out of the build context. It keeps node_modules, .git, and secret files out of builds, making them faster and safer.
What .dockerignore does
When you run docker build ., the CLI packages the directory (the build context) and sends it to the builder before any Dockerfile instruction runs. .dockerignore removes matching paths from that package, so they are never transferred, never reachable by COPY or ADD, and never able to invalidate the build cache.
A production template
# Dependencies: install inside the image, never copy from the host**/node_modules**/__pycache__**/*.pyc.venv # Build output: rebuild inside the imagedistbuild.nexttarget # Version control and editor files.git.gitignore.vscode.idea # Secrets: never in an image.env.env.*!.env.example*.pem*.key # Tests and docscoverage**/*.test.js**/*.spec.jsdocs*.md!README.md # OS noise and logs.DS_Store*.logHow the pattern rules work
- Patterns are relative to the context root, and one pattern per line.
*matches within one directory level, while**matches any number of levels.- A line starting with
!re-includes a path, and the last matching line wins. node_moduleson its own only matches at the root, so use**/node_modulesin monorepos.- The builder still reads the Dockerfile even if you list it, so ignoring it only stops
COPYfrom seeing it.
Measure the effect
# BuildKit prints the context transfer sizedocker build --progress=plain . 2>&1 | grep "transferring context"# #2 transferring context: 2.31MB (was 890MB before .dockerignore)Common MistakeForgetting
.env. WithCOPY . .and no ignore rule, real credentials get baked into an image layer and stay readable withdocker historyand layer extraction.
TipCreate
.dockerignorebefore the first Dockerfile. It is far easier than auditing old images later.
Frequently Asked Questions
Does .dockerignore make the image smaller or only the build faster?
Both, in different ways. It shrinks the context transfer, which speeds every build, especially on remote builders and CI. It also stops unwanted files from being copied, but only if your COPY instructions would otherwise have picked them up, so it works best paired with specific COPY paths.
Why is my ignored file still found by COPY?
Usually a pattern problem. A bare name like node_modules only matches at the context root, and a later "!" rule can re-include a path. Use **/name for any depth and check rule order, since the last matching line wins.
Is .dockerignore the same as .gitignore?
The syntax is similar but not identical. Docker uses Go filepath matching with its own ** and ! handling, and it does not read .gitignore at all, so you must maintain both files.