Start learning free

LESSON 151 OF 188 · BACKEND: SHIPPING IT

Install Before You Copy in Python

Practice

The base image has Python, but nothing of the shop. COPY copies files from the shop's folder on your computer, where you run docker build, into the image: COPY source destination. A . as the destination is the image's current folder, /app thanks to WORKDIR. RUN runs a command inside the image while it is being built, and keeps what the command changed.

Each line of a Dockerfile makes a layer, a saved change to the image, and Docker keeps the layers in a cache. On the next build it reuses a layer, CACHED, as long as the line and the files it copies have not changed. From the first line that changed, every line runs again. So the order matters: what changes rarely goes at the top, what changes often at the bottom.

Here is the same idea for a program built on Node.js: its package list, package.json, is copied and installed first, and the code last.

dockerfile = (
    "FROM node:22-slim\n"
    "WORKDIR /srv\n"
    "COPY package.json .\n"
    "RUN npm install\n"
    "COPY . .\n"
)

The check builds your image, then changes app.py and builds again. When your lines are right, it prints:

$ docker build -t shop .
[1/6] FROM python:3.13-slim
[2/6] WORKDIR /app
[3/6] ENV PYTHONUNBUFFERED=1
[4/6] COPY requirements.txt .: copies requirements.txt into /app
[5/6] RUN pip install -r requirements.txt: installs Flask 3.1.3, gunicorn 23.0.0, requests 2.34.1
[6/6] COPY . .: copies app.py, requirements.txt, Dockerfile into /app
In the image: /app/requirements.txt, /app/app.py, /app/Dockerfile
You change app.py and build again:
[1/6] FROM python:3.13-slim: CACHED
[2/6] WORKDIR /app: CACHED
[3/6] ENV PYTHONUNBUFFERED=1: CACHED
[4/6] COPY requirements.txt .: CACHED
[5/6] RUN pip install -r requirements.txt: CACHED
[6/6] COPY . .: runs again, app.py changed
pip install was CACHED: a change to the code does not install the packages again

Your task: after the three lines of the base, add three lines to the string dockerfile: copy requirements.txt into the current folder, install the packages with pip install -r requirements.txt, then copy the whole shop folder into the current folder. A change to app.py must leave the install CACHED.


Assignment
Follow the Coding Tutorial to add the COPY, RUN and COPY lines to the shop's Dockerfile, in that order.


Hint
In COPY source destination, a dot as the source means everything in the shop's folder, and a dot as the destination means /app. pip can only read requirements.txt once a line above it has copied the file in.


STEP 1 OF 3
    Ctrl + Enter to check

    Ship Dockerfile Install in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free