What is the best way to order Dockerfile instructions?

· Category: Docker

Short answer

Order Dockerfile instructions from least to most frequently changing. Put base image selection and dependency installation early, and copy application code last. This maximizes layer cache reuse.

How it works

Docker builds each instruction into a layer and caches it. When a layer changes, all subsequent layers must be rebuilt. By placing stable instructions first, you reduce the number of layers that need rebuilding during development.

Example

FROM python:3.11-slim          # Least frequent
WORKDIR /app
COPY requirements.txt .        # Changes when dependencies update
RUN pip install -r requirements.txt
COPY . .                       # Most frequent: application code
CMD ["python", "app.py"]

Why it matters

Optimal ordering can reduce build times from minutes to seconds during iterative development. It also reduces CI resource usage and speeds up developer feedback loops.

Tips

  • Install system dependencies before application dependencies.
  • Use RUN to combine related setup steps.
  • Place EXPOSE, ENV, and LABEL near the top since they change infrequently.

Common issues

  • Copying the entire project before installing dependencies invalidates the cache on every code change.
  • Putting ARG too early can unexpectedly invalidate caches when build arguments change.
  • COPY . . is a common cache-buster; be as selective as possible.