.dockerignore Like a Pro
A tight .dockerignore shrinks the build context, speeds up builds, and keeps secrets and junk out of your image.
Every docker build tars up the build context and ships it to the daemon before anything runs. If your .git folder and node_modules go along for the ride, you are paying for it on every build — and risking baking secrets into the image via a stray COPY . ..
Treat it like a security control, not a nicety
- Secrets —
.env,*.pem,.aws/, credentials must never enter the context. - Bloat —
node_modules,.git, build output, test coverage. - Noise — editor folders, OS files, local logs.
Whitelist when it gets messy
For a large monorepo, flipping the logic is cleaner: ignore everything with *, then un-ignore exactly what the build needs with ! patterns. You end up with a tiny, auditable context.
Example
# .dockerignore — whitelist style for a monorepo service
**
# Then allow only what THIS image needs
!package.json
!package-lock.json
!src/
!tsconfig.json
# Never, ever these (belt and suspenders)
.env
.env.*
*.pem
.git
.awsWhen to use it
- A developer reduces build context from 900 MB to 2 MB by adding node_modules, .git, and dist to .dockerignore.
- A team prevents accidentally leaking .env files with API keys into images by listing them in .dockerignore.
- A monorepo project uses per-service .dockerignore files to exclude sibling packages each service does not depend on.
More examples
Comprehensive .dockerignore file
Excludes VCS history, dependencies, build artifacts, secrets, tests, and Docker files themselves from the build context.
# .dockerignore
.git
.gitignore
node_modules
npm-debug.log*
dist
build
coverage
.env
.env.*
*.test.ts
*.spec.ts
Dockerfile*
docker-compose*
.dockerignoreMeasure context size before and after
Compares the raw directory size with the reported build context size to quantify the effect of .dockerignore.
# Measure what WOULD be sent without .dockerignore
du -sh .
# After adding .dockerignore, check the actual context size
docker build -t test . 2>&1 | grep 'Sending build context'Re-include specific file from excluded dir
Excludes entire directories with broad patterns, then uses ! to selectively re-include only the required files.
# .dockerignore
certs/
!certs/bundle.pem
scripts/
!scripts/entrypoint.sh
Discussion