Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 111 of 8022. Docker Image LifecycleFree lesson

Optimizing Instruction Ordering for Cache Hits

Arrange Dockerfile instructions from least frequently changed to most frequently changed to maximize the efficiency of the Docker build cache mechanism.

In this lesson, you will learn how to arrange your Dockerfile instructions to maximize build speed by leveraging the Docker cache.

The Mechanics of the Cache

When you build a Docker image, Docker processes your Dockerfile line by line. For each instruction, it checks if a layer with that specific command already exists in its local cache. If it finds a match, it skips the execution and reuses the existing layer. However, if one instruction changes—or if a file copied into the image changes—the cache is invalidated for that layer and all subsequent layers.

To keep your builds lightning-fast, you should follow the "Least Frequently Changed to Most Frequently Changed" rule.

A Practical Example

Imagine you are building a Python application. Your requirements.txt file changes rarely, but your application source code changes every time you fix a bug. If you copy your entire project folder before installing dependencies, Docker will re-run the pip install command every time you change a single line of code.

Instead, structure your Dockerfile like this:

# 1. Base image (rarely changes)
FROM python:3.9-slim

# 2. Dependency management (changes infrequently)
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

# 3. Source code (changes frequently)
COPY . .

CMD ["python", "app.py"]

By placing the COPY requirements.txt and RUN pip install instructions before copying the rest of your source code, you ensure that as long as your dependencies remain the same, Docker will reuse the cached layer containing your libraries. It will only execute the final COPY . . step when you modify your actual application code, saving you precious minutes during development.

If you had put COPY . . at the top, the cache would break at the very first layer, forcing Docker to re-download and re-install all your dependencies on every single build. Always keep your static configuration and dependency installations near the top and your volatile source code near the bottom.

Key Takeaway: To optimize your build cache, structure your Dockerfile with stable, rarely changing instructions at the top and volatile, frequently changing instructions at the bottom.