Challenge 2: Reorder for Better Caching — Possible Solution ==================================================================== COPY requirements.txt . RUN pip install -r requirements.txt COPY . . WHY THIS WORKS AS AN ANSWER ------------------------------ requirements.txt (the dependency manifest) is copied FIRST, on its own, followed immediately by pip install — this means the pip install layer's cache only gets invalidated when requirements.txt itself actually changes, exactly the same principle this chapter's npm example demonstrated. The full COPY . . (bringing in the rest of the application's source code) now happens LAST, after dependencies are already installed. A change to any Python source file only invalidates this final COPY layer — the pip install layer above it stays cached and is reused, since nothing about requirements.txt changed. Compare this to the original ordering, where COPY . . came first: any source change would invalidate that layer, and therefore force pip install to re-run on literally every build regardless of whether dependencies were ever touched.