Course contentsShow
← Cloud and Infrastructure
Lesson 1019 of 2,98920. Docker in DepthFree lesson

Optimizing Layer Order

Placing frequently-changing instructions last to maximize cache hits during builds.

Optimizing Layer Order

What you'll learn: How to arrange Dockerfile instructions so that frequently-changing steps come last, maximizing cache reuse and speeding up your builds.


Why Order Matters

Docker builds each instruction sequentially and caches every layer it creates. Here's the catch: when one instruction changes, Docker invalidates the cache for that layer and all layers after it. This means everything downstream gets rebuilt, even if those instructions haven't changed.

The Golden Rule

Place stable, rarely-changing instructions at the top of your Dockerfile and put frequently-changing instructions at the bottom. This way, most of your layers stay cached between builds.

Bad example:

FROM python:3.9
COPY . /app
RUN pip install -r requirements.txt

If you change a single line of application code, Docker rebuilds both the COPY layer and reinstalls all your dependencies—even though requirements.txt didn't change!

Better example:

FROM python:3.9
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app

Now dependency installation stays cached when you modify application code. Only the final COPY layer rebuilds.

The Layering Strategy

Think of your Dockerfile like a pyramid: foundation first, details last. Install system packages early, install dependencies next, copy application code last. Your code changes daily; your base OS and libraries change monthly.

Key Takeaway:
Arrange Dockerfile instructions with stable operations first and frequently-changing operations last to maximize layer cache hits and dramatically reduce build times.