Docker
devopsdockerGuideBeginner
The .dockerignore File & Build Optimization
Complete guide to using .dockerignore to exclude unnecessary files from the build context, speed up builds, and protect secrets.
Verified: 2026-09-30
Tested on:docker 27.x
Platforms:
linuxmacoswindows
#docker#dockerignore#optimization#security#devops
The .dockerignore file tells the Docker CLI which files and directories to exclude when packing the Build Context to send to the Docker daemon.
Why .dockerignore is Critical
- Faster Build Times: Prevents transferring gigabytes of local files (like
node_modulesor.git) across the Docker daemon socket. - Deterministic Builds: Ensures local platform binaries (
node_modulesbuilt on macOS) do not leak into Linux containers. - Security: Prevents accidental inclusion of
.envfiles, SSH keys, credentials, and local logs into image layers.
Recommended .dockerignore Template
# Git & version control
.git
.gitignore
# Dependencies
node_modules
npm-debug.log
yarn-error.log
pnpm-lock.yaml
# Build outputs & caches
dist
build
.next
.turbo
coverage
.cache
# Environment variables & secrets
.env
.env.*
!.env.example
*.pem
*.key
id_rsa
# IDE & OS files
.vscode
.idea
.DS_Store
Thumbs.db
# Docker files
Dockerfile*
docker-compose*.yml
.dockerignore
README.mdPattern Matching Rules
- Line starting with
#is a comment. - Leading
/matches paths relative to root context. - Wildcards
*match zero or more characters. **matches any number of directories recursively.!exception prefix overrides previously matched patterns.
Related Guides
Docker Multi-Stage Builds
Complete guide to optimizing image sizes, stripping build tools, caching dependencies, and creating secure production images using multi-stage builds.
Docker Health Checks & Probes
Complete guide to Docker HEALTHCHECK instructions, health status monitoring, interval, timeout, retries, and integration with Docker Compose and orchestration.