← Recipes

阅读中文版本

Keep Docker Build Context Small

Add a .dockerignore that excludes node_modules, build output, VCS data, and secrets so the context is small and no secret can be copied accidentally.

~25 mindockercisecurity

Task

Reduce build context size and prevent secrets from entering the image via .dockerignore.

When to use this

The build context includes node_modules, .git, and a local .env, so builds are slow and a secret can end up inside the image.

Prerequisites

  • A Dockerfile with a COPY step
  • Knowledge of what the build actually needs

Steps

1. Add a .dockerignore that mirrors the ignore file used by the toolchain.

Expected output: Unneeded files never enter the context.

2. Exclude VCS directories, build output, and local env files.

Expected output: Rebuilds are fast and secrets stay out.

3. Use a specific COPY of only the needed paths rather than COPY . .

Expected output: Only intended files are copied.

4. Verify the built image contains no test or secret files.

docker run --rm app:test ls -la /app

Expected output: The image is minimal and safe.

Troubleshooting

Problem

Missing file in the image

Solution

A too-broad ignore pattern can exclude needed files; check the pattern and copy the required paths explicitly.

Problem

Secret already in an old image

Solution

Rotate the secret; removing it from the context does not remove it from images already built.

Limitations

  • .dockerignore reduces context but does not create a secure build; never rely on it to keep secrets out of reach of COPY.
  • A byte-identical context does not guarantee cache reuse if the base image or builder changes.

Context

Reduce build context size and prevent secrets from entering the image via .dockerignore. The build context includes node_modules, .git, and a local .env, so builds are slow and a secret can end up inside the image.

Steps

  1. Add a .dockerignore that mirrors the ignore file used by the toolchain. Expected: Unneeded files never enter the context.
  2. Exclude VCS directories, build output, and local env files. Expected: Rebuilds are fast and secrets stay out.
  3. Use a specific COPY of only the needed paths rather than COPY . . Expected: Only intended files are copied.
  4. Verify the built image contains no test or secret files. Expected: The image is minimal and safe.
# .dockerignore
node_modules
dist
.git
.env
*.log
coverage

Verify

  • Unneeded files never enter the context.
  • Rebuilds are fast and secrets stay out.
  • Only intended files are copied.
  • The image is minimal and safe.

Limits

  • .dockerignore reduces context but does not create a secure build; never rely on it to keep secrets out of reach of COPY.
  • A byte-identical context does not guarantee cache reuse if the base image or builder changes.