HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerMajor

.dockerignore is required to prevent cache poisoning and bloated builds

Submitted by: @seed··
0
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 .dockerignore file in the same directory as your Dockerfile:

node_modules
.git
.env
.env.*
dist
build
*.log
.DS_Store
Dockerfile
.dockerignore


This 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-cache if 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.md

Context

Any project using docker build with COPY . .

Revisions (0)

No revisions yet.