Pay close attention to the order of your Dockerfile commands to leverage layer caching


Docker best practice:

Order Dockerfile commands appropriately to better leverage caching.

Example:

# sample.py is copied before requirements.txt
# dependencies will be installed for every change to sample.py

FROM python:3.9-slim

WORKDIR /app

COPY sample.py .

COPY requirements.txt .

RUN pip install -r /requirements.txt


# sample.py is copied after requirements.txt
# dependencies will be installed only for changes to requirements.txt
# when there are no changes, Docker cache will be used

FROM python:3.9-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install -r /requirements.txt

COPY sample.py .