.dockerignore Best Practices That Actually Matter
A bloated build context slows every build, wrecks your cache, and quietly leaks secrets into images. Here's how to keep it lean.
Key takeaways
- A .dockerignore file controls what goes into the build context sent to BuildKit.
- Always exclude .git, dependency folders, build output, and secrets such as .env and key files, using **/ patterns for nested paths.
- Patterns follow Go filepath.Match rules and the last matching line wins, so put ! exceptions after the rule they override.
On this page
Put a .dockerignore at the root of the build context and exclude .git, dependency folders (**/node_modules), build output, and secrets (.env, *.pem, *.key). Patterns follow Go's filepath.Match rules plus **, and the last matching line wins. A lean context means faster build starts, cache hits, and no credentials baked into layers.
Verified against
Docker Engine 29.9 with BuildKit, against the docs.docker.com build context (.dockerignore), build secrets and Engine 29 release notes pages. Checked October 2026.
Most people write a .dockerignore once, copy it from an old project, and never look at it again. Then they wonder why builds take 40 seconds to even start, why the cache never hits, and why a Go service ships in a 900MB image. The file controls what gets sent to the builder before a single instruction runs, so you pay for getting it wrong on every build.
The build context is the whole point
When you run docker build ., that trailing . is the build context. The client packages everything in that directory and ships it to the builder. COPY and ADD can only reference files inside it. So the size of the context sets a floor on how slow your build starts.
Run a build in a repo with a fat node_modules and a long .git history and BuildKit tells you: transferring context: 512MB. That transfer happens before Dockerfile line one. On a laptop it's annoying. In CI, with a remote builder or a slow disk, it's the difference between a 30-second pipeline and a 4-minute one.
The .dockerignore file lives at the root of the context and tells the client what to leave out. Fewer files sent means a faster start and, just as important, a cache that actually works.
Syntax, and why it is not .gitignore
The patterns look like .gitignore, and that resemblance trips people up. Docker's docs say matching uses Go's filepath.Match rules, plus a special ** wildcard, not git's wildmatch engine:
# .dockerignore
# comments start with a hash
**/node_modules
**/*.log
.git
!keep-this.log
- Patterns are matched against paths from the context root. A bare
node_modulescatches the top-level directory; in a monorepo, use**/node_modulesto catch nested ones too. This is the biggest difference from.gitignore, where a bare name matches at any depth. **matches any number of directories, including zero.**/*.logkills logs at every depth.- A leading
!makes an exception, re-including something an earlier line excluded. - Leading and trailing slashes are ignored, so
docs/anddocsmean the same thing. Don't assume a.gitignorecopied verbatim behaves the same.
The order matters more than people expect. The last line that matches a file decides whether it's in or out. If you exclude *, re-include !src/, and a later broad rule matches again, the file drops out. When an exception isn't working, the fix is almost always moving it below the rule it's fighting.
What to always exclude
Some entries earn their place in nearly every project:
.gitand.gitignore: history and metadata the image never needs..gitalone is often the biggest single thing in the context.node_modules,vendor,venv,__pycache__: dependency and build artifacts you rebuild inside the image anyway.dist,build,target,*.o,*.pyc: local compiler output that would clash with what the build produces fresh..env,*.pem,*.key,secrets/,credentials.json: the ones that keep you up at night. More on this below..vscode,.idea,.DS_Store,*.swp: editor and OS junk.README.md,docs/,*.md, test fixtures, large sample data: anything the runtime doesn't touch.Dockerfile,docker-compose.yml,.github/: build and CI config the image has no use for. The Dockerfile and.dockerignoreare still sent to the builder because the build needs them; excluding them only stopsCOPYfrom putting them in the image.
The security angle is the one that bites
The failure mode goes like this. You write COPY . . because it's easy. Meanwhile a .env with a database password sits in the repo root because that's how local dev works. Now that password is baked into an image layer, and it stays there even if a later layer deletes the file. Anyone who pulls the image can unpack the layers and read it.
A .dockerignore that lists .env, *.pem, and secrets/ is a real control here, not hygiene theater. A careless COPY . . can't scoop up a credential that never should have left the developer's machine. For anything the build genuinely needs, use build secrets: Docker's docs state that build arguments and environment variables persist in the final image and are inappropriate for secrets.
$ docker build --secret id=npmrc,src=$HOME/.npmrc .
# Dockerfile
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
Treat this as belt and suspenders. The ignore file stops the accident; scoped COPY and build secrets handle the intentional cases. If you're already fighting build failures, a lean context also makes them easier to reason about, and our Docker troubleshooting guide walks through the common ones.
Cache and multi-stage builds
Every COPY invalidates cache when the copied files change. If your context includes churny junk (logs, local build output, an editor's scratch files), COPY . . misses cache for changes that have nothing to do with your code. Excluding that noise keeps the cache valid until real source changes. A cache that never hits also piles up on CI disks, which is how you end up fixing "no space left on device".
Multi-stage builds don't get you out of this. The .dockerignore applies to the whole build, every stage. A builder stage that does COPY . . still pulls the full unfiltered context if you skipped the ignore file. The clean pattern is to copy narrowly first for dependency resolution, then copy source:
# Dockerfile
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
That first COPY only busts cache when dependencies change, so npm ci stays cached across ordinary code edits. But it only works if node_modules is ignored, otherwise the local one clobbers what npm ci installed.
If one repo has several Dockerfiles with different needs, BuildKit supports a Dockerfile-specific ignore file: build.Dockerfile reads build.Dockerfile.dockerignore, which takes precedence over the root .dockerignore.
The mistake that's worse than a fat context
Excluding something the build actually needs. Someone adds *.md to trim the context, and a Go build that embeds a README.md via //go:embed breaks with a file-not-found that makes no sense until you check the ignore file. Or a broad config/ exclusion drops a config the app reads at startup.
The exception pattern is worth memorizing. Exclude a directory, then re-include the one file you need:
# .dockerignore
config/
!config/production.yaml
Order matters. Put the ! line after the exclusion or it does nothing.
A starter .dockerignore
A solid default for a Node, Python, or Go service. Trim what doesn't apply:
# .dockerignore
# VCS
.git
.gitignore
.gitattributes
# Dependencies / build output
**/node_modules
vendor
venv
.venv
**/__pycache__
**/*.pyc
dist
build
target
**/*.o
# Secrets and env
**/.env
**/.env.*
**/*.pem
**/*.key
secrets/
credentials.json
# Editor / OS
.vscode
.idea
**/.DS_Store
**/*.swp
# Docs, tests, CI
*.md
docs/
.github/
Dockerfile*
docker-compose*.yml
.dockerignore
# Logs and local data
**/*.log
tmp/
testdata/
Questions people ask
Does .dockerignore work like .gitignore?
Not exactly. Docker matches patterns with Go's filepath.Match rules against paths from the context root, plus a ** wildcard for any depth. A bare node_modules in .gitignore matches at every level, but in .dockerignore you should write **/node_modules to be sure nested copies are excluded. Both files use ! for exceptions, and in .dockerignore the last matching line wins.
Can I exclude the Dockerfile in .dockerignore?
Yes. Docker's docs say you can list Dockerfile and .dockerignore themselves; they are still sent to the builder because the build needs them, but COPY, ADD and bind mounts can no longer put them into the image. That keeps build instructions out of production images without breaking the build. Use Dockerfile* to cover variants like Dockerfile.dev.
How do I check what is in my Docker build context?
Watch the transferring context line in BuildKit output to see the size. To list the files, build a throwaway stage with FROM busybox, COPY . /ctx and RUN find /ctx, then run it with --progress=plain and --no-cache. Anything in that listing that you didn't expect, especially .env files or keys, belongs in .dockerignore.
The call we'd make
Write the .dockerignore first, before the Dockerfile, and treat .git, dependencies, and secrets as non-negotiable exclusions. Then verify: run a build, watch the context size BuildKit reports, and unpack a layer or two to confirm nothing sensitive rode along. Two minutes of checking beats finding a leaked key in a published image. A lean context is the cheapest speed and safety win in the whole Docker workflow.
Sources
Cite this article
Kiril Urbonas (2026). .dockerignore Best Practices That Actually Matter. DevOpsNess. Updated 2026-10-31. https://www.devopsness.com/blog/dockerignore-best-practices
[.dockerignore Best Practices That Actually Matter](https://www.devopsness.com/blog/dockerignore-best-practices) (Kiril Urbonas, DevOpsNess, updated 2026-10-31)
More from DevOps
Explore more articles in this category
kaniko CVE-2026-105769: Lookalike ACR Hosts Get Your Azure Token. Rebuild on v1.25.20
A FROM line pointing at a host like x.azurecr.io.attacker.com is enough to make kaniko hand the build's Entra ID token to that host. Which kaniko forks and images are affected, how to find Azure identities in your build pods, and what to rotate.
Sign Container Images With Cosign: Keyless GitHub Actions Workflow, SBOM and In-Cluster Checks
One workflow that builds, signs keylessly with GitHub OIDC, attaches an SBOM and SLSA provenance, plus the Kyverno policy that refuses anything unsigned. Copy it, change three names, ship it.
GitLab CVE-2026-110264: A Second CVSS 10 RCE in Nine Days. Patch to 19.5.1
An unauthenticated regex-compiler RCE reaching back to GitLab 7.0, no workaround, and backports on older branches that fix only the critical bug. The exact version per branch and the commands to get there.
You might have missed
Evergreen posts worth revisiting.