5.1.2.2 Dockerignore Build Outputs
A focused guide to Dockerignore Build Outputs, connecting core concepts with practical Docker and container operations.
Excluding build outputs through .dockerignore prevents locally generated artifacts — compiled binaries, bundled JavaScript, generated documentation — from being unnecessarily transferred as part of the build context, since these are typically regenerated fresh by the Dockerfile's own build steps rather than reused from the host.
Why Local Build Outputs Shouldn't Be in the Context
A Dockerfile performing its own build step produces output specific to the image's own environment; a locally generated build output from the host risks being stale, platform-mismatched, or simply redundant once the image performs the equivalent build step itself.
dist/
build/
target/
*.class
*.o
A Concrete Example of the Problem
If a local dist/ directory from a previous local build is not excluded, and the Dockerfile also generates its own dist/ directory during the build, the two could conflict or the stale local version could be inadvertently included alongside or instead of the fresh one.
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
Excluding the local dist/ directory ensures only the freshly built output, generated by npm run build inside the image, ends up in the final result.
Avoiding Confusing, Stale Artifacts
A stale, locally built artifact accidentally included in an image can cause confusing bugs, where the running application's behavior doesn't match the source code, because it is actually running an outdated build from before the most recent source changes.
docker run --rm myapp cat /app/dist/build-info.json
Verifying that the artifact actually present matches what the current build would be expected to produce helps catch this kind of issue.
Why Excluding Build Outputs Matters
Excluding locally generated build artifacts ensures an image's final contents genuinely reflect a fresh build performed within the image's own controlled environment, rather than an artifact whose provenance is uncertain and whose freshness cannot be guaranteed.