Lecture 25 - Docker for Data Science
==venv, pip and uv gave us an isolated Python
/opt/venvpython:3.14-slim built in 13 secondsdanilofreire/datasci350-example on Docker Hubdocker build -t datasci350-example .
#5 [1/5] FROM docker.io/library/python:3.14-slim
#5 DONE 0.0s
#6 [2/5] WORKDIR /app
#6 CACHED
#7 [3/5] COPY requirements.txt .
#7 CACHED
#8 [4/5] RUN pip install --no-cache-dir -r
requirements.txt
#8 CACHED
#9 [5/5] COPY hello.py .
#9 CACHED
#10 exporting to image
#10 DONE 0.1s# Start from an official Python image
FROM python:3.14-slim
# Create /app inside the image and move into it
WORKDIR /app
# Copy requirements.txt from your computer
# into /app (the "."), then install it
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy hello.py from your computer into /app
COPY hello.py .
# The command that runs when the container starts
CMD ["python", "hello.py"]FROM picks the base image, here Python 3.14 on a slim Debian Linux
WORKDIR creates /app and runs every later step inside itCOPY brings a file from your folder into the imageRUN executes a command while the image is builtCMD sets the command the container runs when it startsrequirements.txt is copied before hello.py, so editing the script does not reinstall the packagesENV, which sets a variable such as PATH, and SHELL, which picks the shell for RUN1. The project starter
data/raw/ is in the repository2. The Dockerfile
3. Run, change, rebuild
-v to get the report out4. When something goes wrong
5. Beyond one Dockerfile
| Criterion | Weight |
|---|---|
Reproducibility: the container builds and the report renders from a clean docker run |
30% |
| Analysis quality: the research question, the method, the interpretation | 30% |
| Communication: clarity of the writing and the visualisations | 20% |
| Code quality: organised, readable, no dead code | 10% |
| Git workflow: meaningful commits from all members, sensible repository structure | 10% |
Run the pull script once and commit data/raw/. If report.qmd calls the API itself, it fails whenever the API is down
scripts/pull_data.py calls the API. report.qmd reads the saved files in data/raw/| Path | What it does |
|---|---|
scripts/pull_data.py |
Calls the World Bank API once and saves the response |
data/raw/ |
The saved snapshot, committed on purpose |
report.qmd |
The Quarto report, with headings that follow the rubric |
requirements.txt |
The pinned Python packages |
Dockerfile |
The instructions that build the image |
.dockerignore |
What stays out of the image |
.gitattributes |
Keeps Linux line endings inside the container |
data/raw/: the raw JSON and a tidy CSVscripts/pull_data.pyIf you add data/raw/ to .gitignore, the build still works. The report fails later, in my clone, because the CSV never reached GitHub: see it happen
requirements.txt for a report# Talking to web APIs
requests==2.32.5
# Data processing (use either, or both)
# DuckDB runs SQL over your CSV files and
# hands the answer back as a pandas
# DataFrame when you call .df() on it.
pandas==3.0.5
duckdb==1.5.5
# Plotting
matplotlib==3.10.8
# Quarto needs these to run Python code
# inside report.qmd
ipykernel==7.2.0
jupyter-client==8.8.0
nbclient==0.10.4
nbformat==5.10.4
pyyaml==6.0.3| Package | What it does |
|---|---|
requests |
Calls the World Bank API |
pandas |
Tidies the data and holds DuckDB’s results |
duckdb |
Runs SQL on the CSV, as in Lecture 22 |
matplotlib |
Draws the figure |
ipykernel |
Starts the Python kernel for Quarto |
jupyter-client |
Sends your code to the kernel |
nbclient, nbformat |
Run and save the notebook Quarto builds |
pyyaml |
Quarto needs it to run Python code |
report.qmd needs to renderimport duckdb
import matplotlib.pyplot as plt
data = duckdb.sql(
"SELECT country, year, value "
"FROM 'data/raw/life_expectancy.csv' "
"ORDER BY country, year"
).df()
print(f"Loaded {len(data)} rows covering "
f"{data['country'].nunique()} countries.")
fig, ax = plt.subplots(figsize=(7, 4))
for country, subset in data.groupby("country"):
ax.plot(subset["year"], subset["value"])
[...]
plt.show()output/report.html
duckdb, pandas and matplotlib, and a kernel Quarto can startquarto binary itselfdata/raw/life_expectancy.csv at that exact relative pathembed-resources: true puts the figures inside the HTML
output/report.html is the single file your container must produce, and the one I gradeLoaded 96 rows covering 4 countries.echo: true, which shows your code in the report
Dockerfile# 1. Base image
FROM ubuntu:24.04
# 2. Environment and shell
ENV DEBIAN_FRONTEND=noninteractive
SHELL ["/bin/bash", "-c"]
# 3. System packages
RUN apt-get update && apt-get install -y [...]
# 4. Quarto
RUN ARCH=$(dpkg --print-architecture) && [...]
# 5. Python environment
RUN python3 -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt /project/requirements.txt
RUN pip install --no-cache-dir -r /project/requirements.txt
# 6. Project files
WORKDIR /project
COPY . /project
# 7. Default command
ENV QUARTO_PYTHON=/opt/venv/bin/python
CMD ["bash", "-c", "quarto render report.qmd && [...]"][1/8] to [8/8]ENV, SHELL and CMD only record settings, so they get no numberFROM, ENV, SHELL# We pin the tag to "24.04" rather than "latest".
# "latest" changes over time, and a base image
# that changes breaks reproducibility.
FROM ubuntu:24.04
# DEBIAN_FRONTEND=noninteractive stops apt-get
# from asking questions during the build.
# Nobody is at the keyboard to answer them.
ENV DEBIAN_FRONTEND=noninteractive
# Use bash for the RUN steps below. Docker uses
# the simpler "sh" shell by default.
SHELL ["/bin/bash", "-c"]ubuntu:latest meant 24.04 last year and means 26.04 today, so we pin the tagtzdata is the Ubuntu package that would otherwise stop and ask you for a time zoneubuntu:24.04 is a 29MB download, 108MB once unpackedENV also applies when the container runsSHELL makes every later RUN use bash, and -c passes it a string of commandsubuntu image has no Python, so block 3 installs it.deb file, which needs a Debian-based system like UbuntuRUN apt-get installRUN is one layer
RUN lines here would give six layers and a bigger imageRUN: a later layer cannot shrink an earlier one--no-install-recommends skips optional extras| Package | Why |
|---|---|
ca-certificates |
HTTPS downloads fail without it |
wget |
Fetches the Quarto .deb |
git |
Some Quarto extensions want it |
python3.12 |
The interpreter, version 3.12.3 here |
python3.12-venv |
Ubuntu ships venv separately |
python3-pip |
Installs into the virtual environment |
RUN ARCH=$(dpkg --print-architecture) && \
wget -q "https://github.com/quarto-dev/quarto-cli/releases/download/v1.10.18/quarto-1.10.18-linux-${ARCH}.deb" && \
apt-get update && \
apt-get install -y --no-install-recommends ./quarto-1.10.18-linux-${ARCH}.deb && \
rm quarto-1.10.18-linux-${ARCH}.deb && \
apt-get clean && rm -rf /var/lib/apt/lists/*.deb from GitHub./ tells apt to install the downloaded file, not search its listapt-get update runs again because block 3 deleted the package listsdpkg --print-architecture gives arm64 on a Mac and amd64 on most Windows and Linux laptops, so each downloads the right filepip# Ubuntu protects its own Python installation,
# so we create a virtual environment at
# /opt/venv and install our packages there.
RUN python3 -m venv /opt/venv
# PATH tells the shell where to look for
# programs. Putting /opt/venv/bin first means
# "python" and "pip" refer to the virtual
# environment, without activating it by hand.
ENV PATH="/opt/venv/bin:$PATH"
# We copy requirements.txt on its own, before
# the rest of the project.
COPY requirements.txt /project/requirements.txt
RUN pip install --no-cache-dir -r /project/requirements.txtENV PATH replaces Lecture 23’s source .venv/bin/activatepip install with externally-managed-environment, so we use a virtual environment: Appendix 02COPY puts your requirements.txt inside the image, and pip installs from that copy--no-cache-dir keeps pip’s downloads out of the imageCOPY requirements.txt comes before COPY . /project, so editing report.qmd does not rerun this stepWORKDIR, COPY ., CMD# WORKDIR sets the folder that later
# instructions run inside.
WORKDIR /project
# Copy everything else from your repository into
# the image, including report.qmd and the saved
# data snapshot in data/raw/.
# The .dockerignore file next to this one lists
# what stays out.
COPY . /project
# QUARTO_PYTHON points Quarto at the virtual
# environment's Python.
ENV QUARTO_PYTHON=/opt/venv/bin/python
CMD ["bash", "-c", "quarto render report.qmd && mkdir -p output && cp -a report.html output/ && echo 'Rendered report is in output/report.html'"]COPY . /project copies the folder you build from, the . in docker build
QUARTO_PYTHON tells Quarto which Python to useCMD joins four commands with &&: render, create output/, copy the report there, print a message/project first, because it cannot clear a folder mounted from your laptopCMD list starts with bash, which gives us the shell that && needs.dockerignore# Version control
.git
# Python environments and caches
.venv/
venv/
__pycache__/
# API keys never enter the image
.env
# Quarto working files and rendered output
.quarto/
*.quarto_ipynb
report.html
report_files/
output/
# Operating system clutter
.DS_Store
# NOTE: data/raw/ is deliberately absent. The
# snapshot must reach the image, because
# report.qmd reads it.Dockerfile and commit it.git and the rendered report left out.gitignore keeps files out of Git, and .dockerignore keeps them out of the image
data/raw/ in either filereport.html in the list, every render breaks the cache on COPY . /projecttime docker build --no-cache --progress=plain -t datasci350-project .
#5 [1/8] FROM docker.io/library/ubuntu:24.04
#5 CACHED
#6 [2/8] RUN apt-get update && apt-get install [...]
#6 DONE 36.0s
#7 [3/8] RUN ARCH=$(dpkg --print-architecture) [...]
#7 91.74 Setting up quarto (1.10.18) ...
#7 DONE 92.0s
#8 [4/8] RUN python3 -m venv /opt/venv
#8 DONE 1.3s
#9 [5/8] COPY requirements.txt /project/requirements.txt
#9 DONE 0.0s
#10 [6/8] RUN pip install --no-cache-dir -r [...]
#10 50.70 Successfully installed asttokens-3.0.2 [...]
#10 DONE 51.4s
#11 [7/8] WORKDIR /project
#11 DONE 0.1s
#12 [8/8] COPY . /project
#12 DONE 0.1s
#13 exporting to image
#13 DONE 10.5s
docker build [...] 3:11.77 total--progress=plain prints the full log. Use it when a build fails--no-cache runs every step again, which is how I timed it[1/8] says CACHED because Ubuntu was already on my laptop. Its first download took 38.6 secondsdocker history shows the size of each layerdocker history --format "{{.Size}}\t{{.CreatedBy}}" \
datasci350-project
0B CMD ["bash" "-c" "quarto render [...]
0B ENV QUARTO_PYTHON=/opt/venv/bin/python
81.9kB COPY . /project
0B WORKDIR /project
421MB RUN pip install --no-cache-dir -r [...]
4.1kB COPY requirements.txt [...]
0B ENV PATH=/opt/venv/bin:/usr/local/sbin:[...]
15.6MB RUN python3 -m venv /opt/venv
459MB RUN ARCH=$(dpkg --print-architecture) [...]
169MB RUN apt-get update && apt-get install [...]
0B SHELL [/bin/bash -c]
0B ENV DEBIAN_FRONTEND=noninteractive
108MB ADD file:0387b3d029de8fa08[...] in /
0B [...]docker history lists one row per layer, newest at the topubuntu:24.04 base is only 108MBENV, SHELL and CMD only set metadata. WORKDIR gets a step number but adds 0BCACHED step skips the download as well as the workdocker images reports 1.52GB on disk and 347MB content, because content size is measured compressedtime docker run --rm \
-v "$(pwd)/output:/project/output" \
datasci350-project
Starting python3 kernel...Done
Executing 'report.quarto_ipynb'
Cell 1/1: 'fig-demo'...Done
[...]
Output created: report.html
Rendered report is in output/report.html
docker run [...] 3.237 total
ls -la output
-rw-r--r-- 1 dafreir staff 1314625 report.html| Part | What it does |
|---|---|
--rm |
Deletes the container when it exits |
-v host:container |
Connects a folder on your machine to one inside the container |
datasci350-project |
The image to start |
-v (volume): your laptop’s folder goes left of the colon, the container’s on the right$(pwd) is your current folder. Use ${PWD} in PowerShell or %cd% in the old Windows terminal-v ./output:...--rm deletes the container as soon as it finishes--rm then deleted the container, and the report with itoutput/ inside the container shows the report was there:>/dev/null 2>&1 hides Quarto’s messages, so only the file listing showsWithout -v, the report is deleted with the container. After every run, check ls output and the file’s timestamp
report.qmd and built again:time docker build --progress=plain -t datasci350-project .
#4 transferring context: 4.95kB done
#5 [1/8] FROM docker.io/library/ubuntu:24.04
#5 DONE 0.0s
#6 [3/8] RUN ARCH=$(dpkg --print-architecture) [...]
#6 CACHED
#7 [2/8] RUN apt-get update && apt-get install [...]
#7 CACHED
#8 [5/8] COPY requirements.txt /project/requirements.txt
#8 CACHED
#9 [4/8] RUN python3 -m venv /opt/venv
#9 CACHED
#10 [6/8] RUN pip install --no-cache-dir -r [...]
#10 CACHED
#11 [7/8] WORKDIR /project
#11 CACHED
#12 [8/8] COPY . /project
#12 DONE 0.0s
docker build [...] 0.666 totalreport.qmd changed, so only COPY . /project ran againpip install stayed cached, because requirements.txt did not change[n/8] labels show the real order. The # numbers are just log IDsrequirements.txt instead, and the cache misses at [5/8], so pip and every later step run againdata/raw/ to .gitignore, committed, and cloned the repository into a new folder:Always test from a fresh clone. Your own folder still has the files you forgot to commit
docker run --rm -v "$(pwd)/output:/project/output" \
datasci350-project-nodata
Starting python3 kernel...Done
Executing 'report.quarto_ipynb'
Cell 1/1: 'fig-demo'...
An error occurred while executing the following cell:
[...]
data = duckdb.sql("SELECT country, year, value "
"FROM 'data/raw/life_expectancy.csv' [...]").df()
[...]
IOException: IO Error: No files found that match
the pattern "data/raw/life_expectancy.csv"
WARN: Error encountered when rendering files
exit code: 1git add data/raw/ and git commitgit ls-files data/raw should then print two file namesduckdb==1.5.5 to duckdb==1.5.9 and built:#10 [6/8] RUN pip install --no-cache-dir -r [...]
#10 0.818 Collecting pandas==3.0.5 [...]
#10 1.302 ERROR: Could not find a version that
satisfies the requirement duckdb==1.5.9
(from versions: [...] 1.5.4, 1.5.5, 1.5.6.dev36,
1.6.0.dev379, 2.0.0.dev2609121639)
#10 1.302 ERROR: No matching distribution found
for duckdb==1.5.9
Dockerfile:85
--------------------
84 | COPY requirements.txt /project/requirements.txt
85 | >>> RUN pip install --no-cache-dir -r /project/requirements.txt
--------------------
ERROR: failed to build: failed to solve: process
"/bin/bash -c pip install [...]" did not complete
successfully: exit code: 1[6/8] is the step that failedDockerfile:85 and the >>> marker point to the line[1/8] to [5/8] stay cached, so the fix only reruns pipCMD. Here, bash opens a shell instead of rendering:-it opens an interactive session: -i keeps input open and -t gives you a terminaldocker exec -it <container> bash opens a shell in a container that is already runningrequirements.txt and rebuild insteaddocker logs <container> shows the output of a container running in the background$ docker ps -a
CONTAINER ID IMAGE STATUS
5594bb583fbd hello-world Exited (0) 2 hours ago
$ docker system df
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 7 1 10.88GB 4.029GB (37%)
Containers 1 0 0B 0B
Build Cache 37 0 3.046GB 1.403GB
$ docker rm 5594bb583fbd
$ docker rmi datasci350-project-nodata
[...]
$ docker system prune
[...]
Total reclaimed space: 1.931GB
$ docker system df
Images 4 0 3.217GB 1.97GB (61%)
Containers 0 0 0B 0B
Build Cache 8 0 1.643GB 0B| Command | What it removes |
|---|---|
docker ps -a |
Nothing, it lists all containers |
docker rm <id> |
One stopped container |
docker rmi <image> |
One image |
docker system df |
Nothing, it reports what is using space (df = disk free) |
docker system prune |
Stopped containers, unused networks, dangling images, build cache |
docker system prune -a |
All of the above plus every image not in use |
docker ps -a, and the first few characters are enoughdocker run --rm keeps old containers from piling updocker system prune -a deletes every image no running container is using. Read the prompt before you type y
scipy-notebook takes 5.28GB on diskr-ver, rstudio, tidyverse, verse, geospatialLike our project, scipy-notebook starts FROM Ubuntu, with a few smaller Jupyter images in between. Docs
For the project, write your own Dockerfile. A 5GB image to read one CSV is far more than you need
buildx command builds for both chip types and pushes the image:Use your clone of the starter. Step 2 takes about a minute
seaborn==0.13.2 under duckdb==1.5.5 in requirements.txtdocker build -t datasci350-project .CACHEDreport.qmd, add import seaborn as sns under import duckdbprint(f"seaborn {sns.__version__}") under the Loaded printdocker run --rm -v "$(pwd)/output:/project/output" datasci350-projectoutput/report.html and find the line seaborn 0.13.2Solution and captured output: Appendix 01
What to look for:
[1/8] to [4/8] stay CACHED[5/8], because requirements.txt changedpip install runs again for less than a minuteCOPY . /project and takes secondsDockerfileDockerfile has seven blocks, from the base image to CMD.dockerignore keeps .git, output/ and .env out of the imageCOPY requirements.txt comes before COPY . /project, so rebuilds take less than 1 second-v, the report is deleted with the containerdata/raw/ is not committed, the build works but the run failsdocker run -it ... bash lets you look inside the containerdocker system prune frees disk spaceIf git clone, docker build and docker run -v work from a fresh folder and the report opens, the container part of your project is done
No class on Thursday 26 November (Thanksgiving)
Lecture 26 (1 December) is revision. Bring your repository and questions, and we will build containers together
Quiz 05 (3 December) covers Lectures 21, 22, 23 and 25. Assignment 10 is due the same day
The final project is due on 8 December
Before then:
git ls-files data/raw. It should print two file namesgit shortlog -sn. Every group member should appearStep 1, in requirements.txt:
Steps 4 and 5, in the demo chunk of report.qmd:
import duckdb
import seaborn as sns
import matplotlib.pyplot as plt
data = duckdb.sql(
"SELECT country, year, value "
"FROM 'data/raw/life_expectancy.csv' "
"ORDER BY country, year"
).df()
print(f"Loaded {len(data)} rows covering "
f"{data['country'].nunique()} countries.")
print(f"seaborn {sns.__version__}")Step 7, in the rendered report:
CACHED (2 seconds), back to 347MB and 53 packagesSteps 2 and 3, the rebuild:
#5 [1/8] FROM docker.io/library/ubuntu:24.04
#5 DONE 0.0s
#6 [3/8] RUN ARCH=$(dpkg --print-architecture) [...]
#6 CACHED
#7 [2/8] RUN apt-get update && apt-get install [...]
#7 CACHED
#8 [4/8] RUN python3 -m venv /opt/venv
#8 CACHED
#9 [5/8] COPY requirements.txt /project/requirements.txt
#9 DONE 0.0s
#10 [6/8] RUN pip install --no-cache-dir -r [...]
#10 18.77 Downloading seaborn-0.13.2-[...].whl (294 kB)
#10 49.45 Successfully installed [...] seaborn-0.13.2 [...]
#10 DONE 50.0s
#11 [7/8] WORKDIR /project
#11 DONE 0.1s
#12 [8/8] COPY . /project
#12 DONE 0.1s
docker build [...] 57.726 total[5/8]IOException: No files found that match [...] life_expectancy.csv
data/raw/ was never committed. Run git add data/raw/ and commit, then check with git ls-files data/raw.
No matching distribution found for duckdb==1.5.9
That version does not exist. Pin one that pip index versions duckdb lists.
ls: output: No such file or directory
You forgot -v. Add -v "$(pwd)/output:/project/output" (${PWD} in PowerShell). Linux prints ls: cannot access 'output'.
error: externally-managed-environment
You ran pip install on Ubuntu’s own Python. Use a virtual environment, as in block 5.
failed to read dockerfile: open Dockerfile
You are in the wrong folder. cd into the folder that has the Dockerfile.
NoSuchKernel: No such kernel named python3
ipykernel is missing from requirements.txt. Add ipykernel==7.2.0 back and rebuild.
toomanyrequests: pull rate limit
Docker Hub allows 100 pulls every six hours without an account, 200 with one. Run docker login and build again
# 1. Base image
# FROM chooses the starting point: Ubuntu 24.04,
# the system you saw in the containers lecture.
# We pin the tag to "24.04" rather than "latest".
FROM ubuntu:24.04
# 2. Environment and shell
ENV DEBIAN_FRONTEND=noninteractive
SHELL ["/bin/bash", "-c"]
# 3. System packages
# We do not pin apt versions here. Ubuntu replaces
# a version whenever it ships a security fix, and a
# pin that no longer exists stops the build. The
# base image tag and requirements.txt carry the pins.
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
wget \
git \
python3.12 \
python3.12-venv \
python3-pip && \
apt-get clean && rm -rf /var/lib/apt/lists/*
# 4. Quarto
# Quarto is not in the Ubuntu package list, so we
# download the .deb from GitHub. The version is
# written out in full, so the image you build is
# the image everyone else builds.
RUN ARCH=$(dpkg --print-architecture) && \
wget -q "https://github.com/quarto-dev/quarto-cli/releases/download/v1.10.18/quarto-1.10.18-linux-${ARCH}.deb" && \
apt-get update && \
apt-get install -y --no-install-recommends ./quarto-1.10.18-linux-${ARCH}.deb && \
rm quarto-1.10.18-linux-${ARCH}.deb && \
apt-get clean && rm -rf /var/lib/apt/lists/*cb64771, with comments trimmed. Your clone has them all# 5. Python environment
# Ubuntu protects its own Python installation, so
# we create a virtual environment at /opt/venv and
# install our packages there.
RUN python3 -m venv /opt/venv
# PATH tells the shell where to look for programs.
ENV PATH="/opt/venv/bin:$PATH"
# We copy requirements.txt on its own, before the
# rest of the project. Docker caches each layer.
COPY requirements.txt /project/requirements.txt
RUN pip install --no-cache-dir -r /project/requirements.txt
# 6. Project files
# WORKDIR sets the folder that later instructions
# run inside.
WORKDIR /project
# Copy everything else from your repository into
# the image, including report.qmd and the saved
# data snapshot in data/raw/.
# The .dockerignore file next to this one lists
# what stays out.
COPY . /project
# 7. Default command
# We render first and copy afterwards. Quarto
# clears its output folder before writing, and it
# cannot clear a folder Docker mounted from outside.
# QUARTO_PYTHON points Quarto at the venv's Python.
ENV QUARTO_PYTHON=/opt/venv/bin/python
CMD ["bash", "-c", "quarto render report.qmd && mkdir -p output && cp -a report.html output/ && echo 'Rendered report is in output/report.html'"]docker run command in a file:compose.yaml next to your Dockerfile (docker-compose.yml also works):./output, so you don’t need $(pwd)down removes the container and the network it createddocker compose (with a space). docker-compose (with a hyphen) is the old command