The .dockerignore File

A .dockerignore file keeps unneeded files out of the build context for faster, cleaner and more secure builds.

Syntax# .dockerignore node_modules .git *.log

When you run docker build, Docker sends the entire build context (your folder) to the daemon. A .dockerignore file tells Docker which files to leave out.

Why it matters

  • Speed — a smaller context is sent and processed faster.
  • Smaller images — avoid copying junk like node_modules or logs.
  • Security — keep secrets such as .env files and .git history out of your image.

The syntax is similar to .gitignore: one pattern per line, with * wildcards and # comments.

Example

Example · bash
# A typical .dockerignore for a Node project
node_modules
npm-debug.log
.git
.gitignore
.env
Dockerfile
.dockerignore
dist
coverage

When to use it

  • A developer adds node_modules to .dockerignore to prevent 200 MB of local dependencies from being sent to the daemon on every build.
  • A team excludes .git, .env, and test/ from the build context to keep build times fast and avoid leaking secrets into the image.
  • A monorepo build uses .dockerignore to exclude sibling packages that a particular service's Dockerfile does not need.

More examples

Typical Node.js .dockerignore

Excludes local node_modules, git history, secrets, and test files from the build context sent to the Docker daemon.

Example · bash
# .dockerignore
node_modules
npm-debug.log
.git
.env
*.test.js
coverage/
dist/

Check build context size

The first line of docker build output reports the build context size, so you can measure the effect of .dockerignore.

Example · bash
# Show build context size before adding .dockerignore
docker build -t myapp . 2>&1 | head -3

# After adding .dockerignore, context should be much smaller
docker build -t myapp . 2>&1 | head -3

Negate patterns to re-include files

Uses ! prefix to re-include a specific file from a broadly excluded directory.

Example · bash
# .dockerignore
# Exclude everything in secrets/
secrets/
# But re-include one specific safe config
!secrets/public-config.json

Discussion

  • Be the first to comment on this lesson.