Script Valley
Docker: Complete Course
Building Docker Images with DockerfileLesson 2.4

How to use .dockerignore to speed up builds

.dockerignore file, build context, context size, node_modules exclusion, .git exclusion, pattern syntax

What Gets Sent to the Docker Daemon

Docker build context and .dockerignore

Every docker build command sends a build context — the entire directory — to the Docker daemon before processing a single Dockerfile instruction. A 500MB node_modules folder gets uploaded even if you never use it in the image.

Create a .dockerignore File

Place .dockerignore in the same directory as your Dockerfile. Syntax is identical to .gitignore.

node_modules
.git
.gitignore
*.log
coverage
.nyc_output
dist
.env
.env.*
Dockerfile
.dockerignore
README.md
__tests__
*.test.js

Why This Matters

Without a .dockerignore, a project with a 200MB node_modules folder uploads 200MB to the daemon on every build — even for a one-line code change. With the file, that context drops to the source files only, often under 1MB, cutting build startup from 10 seconds to under a second.

# Check context size before and after
docker build --no-cache -t myapp . 2>&1 | grep "Sending build context"

Additionally, excluding .env and secrets files from the context prevents accidental inclusion in images if a COPY . . instruction is present. Treat .dockerignore as a security control, not just a performance optimization.

Up next

Pushing Docker images to Docker Hub and private registries

Sign in to track progress