How to Cache Layers in Dockerfile for Faster Builds
To cache layers in a
Dockerfile, order your commands so that the most stable instructions come first and the ones that change often come last. Docker reuses layers from previous builds if the commands and their context haven't changed, speeding up the build process.Syntax
A Dockerfile is made of instructions like FROM, RUN, COPY, and ADD. Each instruction creates a new layer. Docker caches these layers and reuses them if the instruction and its context are unchanged.
Key points:
FROM: Base image layer.RUN: Executes commands, creates a layer with changes.COPY/ADD: Adds files, creates a layer.
Layer caching depends on the exact command and the files involved.
dockerfile
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y curl
COPY . /app
RUN make /appExample
This example shows how to order Dockerfile instructions to maximize caching. The apt-get update and install step is first because it changes rarely. Copying app files is later because they change often.
dockerfile
FROM ubuntu:22.04
# Install dependencies (rarely changes)
RUN apt-get update && apt-get install -y curl build-essential
# Copy source code (changes often)
COPY ./src /app/src
# Build the app
RUN make /app/srcCommon Pitfalls
Common mistakes that break caching:
- Changing files copied early in the Dockerfile invalidates all following layers.
- Running commands that always change (like
apt-get updatewithout caching) causes cache misses. - Using
ADDorCOPYwith large directories unnecessarily.
To fix these, order instructions from least to most frequently changed and avoid commands that always produce different results.
dockerfile
### Wrong way: copying source before installing dependencies FROM ubuntu:22.04 COPY ./src /app/src RUN apt-get update && apt-get install -y curl build-essential ### Right way: install dependencies first FROM ubuntu:22.04 RUN apt-get update && apt-get install -y curl build-essential COPY ./src /app/src
Quick Reference
- Order Dockerfile commands so stable layers come first.
- Use
RUNfor installing dependencies early. - Copy source files after installing dependencies.
- Avoid commands that always change (like
dateorapt-get updatewithout caching). - Use
.dockerignoreto exclude unnecessary files from context.
Key Takeaways
Order Dockerfile instructions from least to most frequently changed to maximize cache reuse.
Docker caches each layer if the command and its inputs are unchanged.
Avoid running commands that always produce different results to keep cache effective.
Use .dockerignore to reduce build context and improve caching.
Place dependency installation before copying source code for better caching.