Docker build cache and layers
Topic: Containers core
Summary
Docker caches layers; change one line and everything after rebuilds. Put rarely changed steps first and frequently changed steps last. Use this when optimizing build speed.
Intent: How-to
Quick answer
- Order matters. COPY package.json before COPY . and RUN install so dependency layer is cached when only code changes.
- Each RUN, COPY, ADD creates a layer. Combine RUN commands where it makes sense; avoid unnecessary layers.
- Build cache can be invalidated by parent change or --no-cache. Use .dockerignore to avoid copying files that change often and bust cache.
Prerequisites
Steps
-
Order for cache
Put base and dependency install first; copy source and build last. So code changes do not invalidate dependency layer.
-
Use .dockerignore
Exclude .git, tmp, local env files so COPY . does not pull in unnecessary or changing files.
-
Verify
Change one file; rebuild. Only layers after the change should rebuild. Use docker build --no-cache to test full rebuild.
Summary
Order Dockerfile so stable steps come first; use .dockerignore; verify cache with incremental builds.
Prerequisites
Steps
Step 1: Order for cache
Dependencies first; source and build steps last.
Step 2: Use .dockerignore
Ignore .git, tmp, and env files to keep COPY cache stable.
Step 3: Verify
Rebuild after small change; confirm only later layers rebuild.
Verification
- Code-only change triggers minimal rebuild.
Troubleshooting
Cache busted — Check order and .dockerignore. Slow build — Use multi-stage; reduce layer count.