A useful .dockerignore
.git
node_modules
*.log
.env
.env.*
coverage
dist- Do not send local credentials or unnecessary dependency trees into the build context.
- Adjust exclusions to your actual build requirements.
Make builds faster and images safer by controlling build context, cache invalidation, dependency ordering and final image contents.
Docker can reuse previous build results when an instruction and the inputs it depends on have not changed. Ordering stable dependency-installation steps before frequently changing application source can improve cache reuse.
A cache hit is a performance optimization, not proof that dependencies are current or secure. Rebuild policy still matters.
A .dockerignore file excludes files and directories from the context sent to the builder. Typical exclusions include .git, local dependency folders, editor files, secrets and build outputs that do not belong in the image.
A Dockerfile can use multiple FROM stages. A build stage contains compilers or tooling, while a later runtime stage copies only the produced artifact. Docker documentation recommends multi-stage patterns broadly because they can keep runtime images smaller and reduce unnecessary components.
.git
node_modules
*.log
.env
.env.*
coverage
distFROM golang:1.24-alpine AS build
WORKDIR /src
COPY . .
RUN go build -o /out/app ./cmd/app
FROM alpine:3.20
COPY --from=build /out/app /usr/local/bin/app
CMD ["/usr/local/bin/app"]Goal: Build a small image twice, then change one input and observe which instructions must be rebuilt.
mkdir -p ~/docker-fundamentals/cache && cd ~/docker-fundamentals/cache
printf 'one\n' > stable.txt
printf 'first\n' > changing.txt
printf 'secret-do-not-copy\n' > local-secret.txtcat > .dockerignore <<'EOF'
local-secret.txt
.git
EOF
cat > Dockerfile <<'EOF'
FROM alpine:3.20
WORKDIR /app
COPY stable.txt .
RUN sha256sum stable.txt > stable.sha256
COPY changing.txt .
CMD ["cat","/app/changing.txt"]
EOFdocker build -t gnu-cache:1 .
docker build -t gnu-cache:1 .printf 'second\n' > changing.txt
docker build -t gnu-cache:2 .docker run --rm gnu-cache:2
docker run --rm gnu-cache:2 sh -c 'test ! -e /app/local-secret.txt && echo ignored'Large CI builds are often optimized by separating dependency metadata from rapidly changing application code and using multi-stage runtime images.
Open each answer only after you have tried to answer the question yourself.
To keep unnecessary or sensitive local files out of the build context.
Build tools can remain in an intermediate stage while the final runtime image contains only needed artifacts.
No. Cache reuse is about unchanged build inputs; update/rebuild policy is separate.