Write a Lean .dockerignore
The build context is everything in the directory tree sent to the daemon, minus what .dockerignore excludes. Without one, node_modules, .git and .env are uploaded on every build, COPY . . bakes them into a layer, and a secret ends up in a pushed image.
Procedure
- Create
.dockerignorenext to the Dockerfile (context root, not the Dockerfile's directory if they differ):.git .gitignore node_modules dist build coverage *.log .env .env.* .DS_Store docker-compose*.yml Dockerfile* README.md - Keep anything the build actually needs; excluding
package-lock.jsonorpatches/breaks a cached install silently. - Match by regex on the whole path, not glob-by-name:
**/tmpexcludes nested dirs,tmponly the root one. Use!to re-include:!src/config.example.json. - Rebuild and watch the context size line the builder prints:
docker build . 2>&1 | head -3showstransferring context: 4.2MB. - For BuildKit,
.dockerignorestill governsCOPY; a file excluded from the context cannot be copied even if named explicitly. - Add the same ignores to
.gitignorewhere they overlap, but do not assume.gitignoreis respected — Docker ignores it unless a.dockerignoremirrors it. - Verify no secret is in the context:
docker build --no-cache -t x . && docker save x | tar -tf - | grep -i env.
Pitfalls
- No trailing-slash vs leading-slash confusion:
/appanchors to the context root;appmatches any path segment namedapp. Losing the leading slash can exclude your source. .dockerignoreis read from the context root, not the Dockerfile directory; with-f docker/Dockerfile .the file must be at., notdocker/.- Excluding
node_modulesthen runningCOPY . .without annpm cistep ships an image that cannot run. - A stale
.dockerignorethat excludes a directory you later started importing causesCOPY failed: no source fileswith a confusing message. - Copying the daemon's
docker build - < .from a shell does not honour.dockerignorepatterns the same way; build with a context dir. - Excluding
package.jsonaccidentally breaks caching and the install; review before committing. .dockerignoredoes not shrink the final image if those paths are alsoCOPYed — it only controls the context; the layer is separate.
Verification
docker build . 2>&1 | grep -m1 'transferring context'
docker run --rm --entrypoint sh x -c 'ls -la / | grep -c "\.git"' # 0
The "transferring context" figure drops to a few MB and no .git/.env exists inside the image. Report the context size before and after.