Skip to Content

.dockerignore & Build Context

When to use

Control what files are sent to the Docker daemon during build; smaller context = faster build + smaller chance of leaking secrets.

Analogy

.dockerignore is the packing list - you don’t want your entire house in the box; only what’s needed for the trip.

Data-flow diagram

  .dockerignore
    **/node_modules
    **/.git
    **/target
    **/*.log
    secrets/
    .env
    *.tmp
  $ docker build -t myapp .  # daemon receives only files NOT ignored

Deep explanation

The build context is the directory tree passed to the Docker daemon by docker build. With .dockerignore, list patterns to exclude (similar to .gitignore). Critical exclusions: .git (huge, may include secrets), node_modules (often rebuilt inside the image), test/coverage files, secrets (.env, secrets/), local logs, IDE files (.idea, .vscode). A too-large context makes builds slow and can accidentally leak secrets (e.g. SSH keys in .ssh/ copied into a layer).

Examples

Example 1

# .dockerignore
.git
.gitignore
node_modules
**/node_modules
**/dist
**/.env
**/coverage
**/*.log
.vscode
.idea
Dockerfile
.dockerignore
README.md

comprehensive ignore list. Especially .git (carries commit history and possibly secrets).

Example 2

docker build --check -t myapp .
# warns if context is suspiciously large

BuildKit —check warns early if you forgot to add to .dockerignore.

Example 3

docker buildx build --progress=plain -t myapp . 2>&1 | head -30

until BuildKit, plain progress shows the context transfer time.

Common mistake

No .dockerignore -> 5GB build context. Accidentally copying .git which may include SSH keys or leaked credentials. Copying .env into the image (secret leak).

Key takeaway

Always include .dockerignore for any nontrivial build; smaller and well-curated context = faster build + smaller leak surface; treat .dockerignore like .gitignore.

Production Failure Playbook

Failure scenario 1: secret-leaked-via-COPY

Failure scenario 2: build-context-8gb