patterndockerMajor
.dockerignore is required to prevent cache poisoning and bloated builds
Viewed 0 times
dockerignorebuild contextcache invalidationnode_modulessecretsgit history
Problem
Without .dockerignore,
COPY . . sends the entire build context to the Docker daemon — including node_modules, .git history, .env files, and local build artifacts. This busts layer caches, inflates image sizes, and risks exposing secrets.Solution
Create a
This prevents these paths from being sent in the build context.
.dockerignore file in the same directory as your Dockerfile:node_modules
.git
.env
.env.*
dist
build
*.log
.DS_Store
Dockerfile
.dockerignoreThis prevents these paths from being sent in the build context.
Why
Docker's build context is a tar archive of all files sent to the daemon before the build starts. Without exclusions, every file modification in excluded directories (like node_modules) changes the context hash and invalidates the COPY layer cache even if nothing meaningful changed.
Gotchas
- .dockerignore syntax is similar to .gitignore but not identical — test with
docker build --no-cacheif uncertain - Excluding .env prevents secrets from leaking into image layers, even if you don't COPY them explicitly
- node_modules should always be excluded — you want the image to install fresh inside the container
- You can use ! to re-include files excluded by a wildcard pattern
Code Snippets
Minimal .dockerignore for a Node.js project
# .dockerignore
node_modules
.git
.gitignore
.env
.env.*
dist/
build/
coverage/
*.log
.DS_Store
Dockerfile*
.dockerignore
README.mdContext
Any project using docker build with COPY . .
Revisions (0)
No revisions yet.