Which Dockerfile ordering makes rebuilds fastest when only your source code changes?
# Option A
COPY . .
RUN pip install -r requirements.txt
# Option B
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .Options
- A
- B (Correct option)
- Both are identical
- Neither uses the cache
Answer
B
Why
Docker builds an image in layers, one per instruction, and reuses (caches) a layer if nothing it depends on changed.
In A, editing any source file changes the COPY . . layer, so every layer after it, including the slow pip install, is rebuilt.
In B, dependencies are installed from requirements.txt alone; that layer is reused until requirements change, and only the final copy reruns.
Remember
Copy what changes rarely first, what changes often last.