Image Layering and Build Caching
On this page
Why Layers Matter
- Layer order drives cache hits and CI speed.
- Bad ordering causes rebuild storms on every commit.
Cache-Friendly Ordering
- Copy lockfiles first, install deps, then copy app code.
- Separate frequently-changing files from stable dependency steps.
Example
FROM python:3.12-slim WORKDIR /app # stable COPY pyproject.toml poetry.lock ./ RUN pip install --no-cache-dir poetry && poetry config virtualenvs.create false && poetry install --only main --no-interaction --no-ansi # changes often COPY . . CMD ["python","-m","app"]
Operational Checks
# show history and layer sizes docker history --no-trunc app:test | head -30 # inspect image config docker image inspect app:test | head -50
Failure Modes
- Large images: build context includes node_modules, logs, .git.
- Cache misses: COPY . . too early invalidates dependency layers.
- Hidden drift: floating base tags change without notice.
.dockerignore Baseline
node_modules .git dist coverage *.log .env