DATASCI 350 - Data Science Computing

Lecture 23 - Dependency Management, Virtual Environments, and Containers

Danilo Freire

Department of Data and Decision Sciences
Emory University

Hello again! 😊

Brief recap 📚

SQL with DuckDB

  • SQL is declarative: you describe the result and the engine plans the work
  • DuckDB reads a Parquet file or a pandas DataFrame by name
  • WHERE filters rows, GROUP BY forms groups, HAVING filters groups
  • NULL means unknown, and COALESCE replaces it with another value
  • A window function adds a group statistic and keeps every row
  • INNER JOIN keeps matches, LEFT JOIN every left row, FULL OUTER JOIN all rows
  • Now that your pipeline works, let’s make it run anywhere! 🤓

Today’s agenda

Lecture overview

Will your code run anywhere else?

1. Dependency management

  • Why working code breaks
  • How to write down what your code needs

2. Virtual environments

  • venv, pip and requirements.txt
  • conda for non-Python software, uv for speed

3. Containers

  • Docker images and containers
  • Docker Desktop’s licence and free alternatives

4. Your first image

  • A six-line Dockerfile, built, run and pushed to Docker Hub
  • A container that renders your report is 30% of the final project grade

Dependency management 📦

Congratulations! 🎉

You have a project 🥳

  • Your code lives on GitHub, pulls data with requests, runs fast with DuckDB, and renders in Quarto
  • Will it run on a new machine, on a colleague’s laptop, or in six months?
  • It depends on the software installed on your laptop, which you never wrote down
  • Dependency management records every package and its version, so others can rebuild the same setup

Why do we need dependency management?

Software changes

  • Libraries change constantly, and even simple code breaks after an update
  • Python 2 to 3 (-c runs a command):
python2 -c 'print "Hello, DATASCI350!"'
Hello, DATASCI350!

python3 -c 'print "Hello, DATASCI350!"'

  File "<string>", line 1
    print "Hello, DATASCI350!"
    ^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to
'print'. Did you mean print(...)?

Definitions

  • Dependencies are the libraries and software your code needs
  • Each package has a name, a version, and possibly its own dependencies
  • A package registry stores packages and metadata: CRAN, PyPI, Conda
  • Dependency management tools (pip, conda) install and record them, so your code still runs later
  • Every tool today writes that list down and replays it elsewhere

The reproducibility crisis

The reproducibility trade-off

  • How far to go depends on who has to rerun your code
  • At minimum, declare your dependencies so others know what you used
  • Manage them with conda, pip or uv
  • Pin exact versions with renv (R) or uv (Python)
  • Host them online with Code Ocean ($$$) or Binder (free, limited)
  • Containerise with Docker or Apptainer for full portability
  • Your final project goes all the way, to a container

How to declare dependencies?

Your analysis uses, e.g., Python, NumPy, pandas and matplotlib. Ask:

  • Which packages do I need?
  • Will this work on my collaborator’s operating system?
  • Can someone else reproduce my results?
  • A package manager declares your dependencies in plain text files
  • Keep them in the repository root, so collaborators install everything in one step
  • The files depend on the tool:
  • Most Python Dockerfiles read requirements.txt, including the project starter’s

Virtual environments

venv and pip: an isolated Python

  • venv ships with Python and creates a folder with its own python and site-packages
  • Installs stay inside it, so two projects can keep two versions of one package
  • Create, activate, install:
mkdir venv-demo && cd venv-demo  # any project folder

python3 -m venv .venv            # create the environment

source .venv/bin/activate        # macOS and Linux
.venv\Scripts\activate           # Windows

pip install requests polars
  • The folder stays out of git (Python 3.13+ adds its own .gitignore). Only the package list is committed
  • which python shows which interpreter is active:
which python
~/venv-demo/.venv/bin/python
  • A path ending in .venv/bin/python means the environment is on. pip list shows what is installed:
pip list
Package            Version
------------------ ----------
certifi            2026.10.23
charset-normalizer 3.5.2
idna               3.20
pip                26.0.1
polars             2.1.0
polars-runtime-32  2.1.0
requests           2.34.2
urllib3            2.8.0
  • Docker images do this too: the project starter runs python3 -m venv /opt/venv, then sets ENV PATH="/opt/venv/bin:$PATH" so later steps use it without activating

requirements.txt: the file you commit

  • pip freeze prints every installed package with its exact version:
pip freeze > requirements.txt
cat requirements.txt

certifi==2026.10.23
charset-normalizer==3.5.2
idna==3.20
polars==2.1.0
polars-runtime-32==2.1.0
requests==2.34.2
urllib3==2.8.0
  • Two packages became seven lines because pip also lists your dependencies’ dependencies
  • The == pins mean “these exact versions”
  • Your collaborator creates an environment and installs from the file:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
  • To leave the environment and delete it:
deactivate
rm -rf .venv
# Talking to web APIs
requests==2.32.5

# Data processing (use either, or both)
pandas==3.0.5
duckdb==1.5.5

Conda in one slide

  • Conda manages environments and packages, including non-Python software: compilers, R, CUDA
conda create --name l23-demo \
  python=3.14 numpy pandas -y
conda activate l23-demo
  • --from-history exports only the packages you asked for:
conda env export --name l23-demo \
  --from-history > environment.yml
  • Others rebuild it from the file:
conda env create --file environment.yml
conda activate l23-demo
  • To delete it, run conda deactivate first, then:
conda env remove --name l23-demo
  • Inside conda, pip freeze can write name @ file:///... lines that fail elsewhere. Use pip list --format=freeze
  • The resulting file:
name: l23-demo
channels:
  - conda-forge
  - defaults
dependencies:
  - pandas
  - numpy
  - python=3.14
prefix: ~/miniconda3/envs/l23-demo
  • Without --from-history, it lists every package, including dependencies of dependencies:
  - _openmp_mutex=4.5=7_kmp_llvm
  - bzip2=1.0.8=h4e30115_10
  - libblas=3.11.0=9_h51639a9_openblas
  - libcxx=23.1.0=h55c6f16_0
  [...]
  • That full list describes one machine exactly but rarely installs on another

What are build strings?

  • A conda build is one compiled binary of a package
  • The same version is compiled separately for each platform, Python version and feature set
  • A full package specification:
numpy=1.21.5=py39h12345_0
└──┬─┘└─┬──┘ └────┬───┘└┬┘
   │    │         │     │
   │    │         │     └─ Build number (0)
   │    │         └─────── Build string (py39h12345_0)
   │    └───────────────── Version (1.21.5)
   └────────────────────── Package name (numpy)
  • --no-builds strips build strings, but macOS-only packages stay in the file
  • For a file that works on other platforms, use --from-history
  • The build string (py39h12345_0) encodes metadata and ends in the build number:
    • Python version (py39, py310)
    • Compiler (gcc9, clang)
    • Features (nomkl, cuda)
  • The platform (linux-64, osx-arm64) is stored separately
  • So libblas=3.11.0=9_h51639a9_openblas from the previous slide will not resolve on Linux

uv: a fast Python package manager

  • uv is a Python package and project manager from Astral, the makers of the Ruff linter
  • Written in Rust, it replaces pip, pip-tools, pipx, poetry, pyenv and virtualenv
  • --python 3.14 picks the version, and uv downloads it if it is missing
  • Install it:
# macOS and Linux: download and run the installer
curl -LsSf https://astral.sh/uv/install.sh | sh

# or with Homebrew
brew install uv

uv --version    # check that it worked
uv 0.11.7 (9d177269e 2026-04-15
aarch64-apple-darwin)
  • uv init creates a project folder with a pyproject.toml, a main.py and a git repository:
uv init l23-uv-demo --python 3.14
cd l23-uv-demo
  • uv add creates .venv, installs the packages and records them in pyproject.toml and uv.lock:
uv add polars requests

Creating virtual environment at: .venv
Resolved 8 packages in 279ms
Installed 7 packages in 8ms
 + polars==2.1.0
 [...]
 + requests==2.34.2

uv: project files and sharing

  • pyproject.toml lists your direct dependencies, for humans to read. Mine after uv add:
[project]
name = "l23-uv-demo"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.14"
dependencies = [
    "polars>=2.1.0",
    "requests>=2.34.2",
]
  • TOML is a config format of key-value pairs and [sections], close to the YAML in Quarto headers
  • Tom Preston-Werner, a GitHub co-founder, created it (“Tom’s Obvious Minimal Language”)
  • uv init also writes .gitignore, .python-version, README.md and main.py, and starts a git repository
  • uv.lock records the exact version and hash of every package. Mine is 182 lines
  • uv writes it for you. Never edit it by hand
  • Commit and push both files. Your collaborator clones the repository and runs uv sync:
uv sync
Resolved 8 packages in 2ms
Checked 7 packages in 1ms

uv run python -c \
  "import polars; print(polars.__version__)"
2.1.0
  • uv run runs inside the project environment, with nothing to activate
  • uv python install 3.14 and uv python pin 3.14 manage Python versions
  • More about uv

uv: handing a project to Docker

  • uv export writes a requirements.txt from your lock file, for Dockerfiles that expect one:
uv export --format requirements-txt --no-hashes

Resolved 8 packages in 2ms
# This file was autogenerated by uv via the
# following command:
#    uv export --format requirements-txt
#      --no-hashes
certifi==2026.10.23
    # via requests
charset-normalizer==3.5.2
    # via requests
[...]
polars==2.1.0
    # via l23-uv-demo
[...]
requests==2.34.2
    # via l23-uv-demo
[...]
  • Without --no-hashes, each line also carries a SHA-256 hash that pip verifies
  • Redirect it into the file your Dockerfile copies:
uv export --format requirements-txt \
  --no-hashes > requirements.txt
  • The # via comments show which package pulled each dependency in. pip freeze has none
  • Already have a requirements.txt? uv pip is a faster drop-in for pip:
uv venv
source .venv/bin/activate
uv pip install -r requirements.txt
  • For a new project, uv init, uv add and uv run are simpler

Containers 🚢

The matrix from hell

Each cell is one combination someone has to test by hand

Source: dotCloud (2013), Docker introduction

Cargo transport before 1960

Sacks, barrels, and crates, each loaded differently at every port

Source: dotCloud (2013), Docker introduction

Also a matrix from hell

Shipping had the same combinatorial problem

Source: dotCloud (2013), Docker introduction

The solution: intermodal containers

A standard box fits every ship, train, and lorry, and nobody opens it in transit

Source: dotCloud (2013), Docker introduction

Docker is a container for your code

Your code, its libraries, and its Python version inside a container

Docker eliminates the matrix from hell

The host only needs Docker, and the image carries everything else

What are software containers?

  • Containers package software so it runs on any system
  • A virtual machine boots a whole operating system. A container carries only the libraries the app needs, so it starts in a second
  • A virtual environment isolates Python packages. A container also holds the system libraries, the interpreter and system tools
  • It runs on any machine with Docker if the image matches the chip: amd64 (Intel/AMD) or arm64 (Apple Silicon)

Lecture 10’s four ingredients of reproducibility: code, data, environment, documentation. A container ships the environment with the code

What is Docker?

  • Docker is the leading container platform
  • An image is a read-only template: operating system, libraries, code and configuration. You build it from a Dockerfile
  • A container is a running instance of an image, and one image can start many
  • A registry such as Docker Hub stores images for you to pull
  • Image is to container as recipe is to dish, or class to object (more here)
  • The syntax borrows from Git (docker pull, docker push) and Linux (docker ps, docker rm)
  • The docker command is a client. A background daemon does the building and running

Client, daemon, and registry

Source: Docker documentation

Docker Desktop and the alternatives

  • Docker Desktop runs Docker on macOS and Windows. Most of you will install it
  • It is free for personal use, education, non-commercial open source, and companies under 250 employees and $10M revenue
  • Docker Hub allows 200 pulls every six hours with a free account, 100 without
  • Docker Engine is open source and free, but runs only on Linux (including WSL)
  • On macOS, an app runs it inside a Linux virtual machine. Docker Desktop, Podman (as podman), Colima, OrbStack (free for personal use) and Rancher Desktop all take the same docker commands

I ran every docker command on these slides through OrbStack. Docker Desktop takes the same commands

Docker Desktop on macOS

Check your installation with hello-world

  • Install Docker Desktop (Docker Engine on Linux), open it once, and run:
docker run hello-world

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
58dee6a49ef1: Pull complete
Digest: sha256:5dd0d3e6e255...
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be
working correctly.
[...]
docker -v

Docker version 29.8.2, build 7fc2dff
  • On Windows, turn on WSL Integration in Docker Desktop: Appendix 03
  • The image was not on my laptop, so Docker pulled it from Docker Hub
  • The output lists four steps:
    • The client contacts the daemon (Docker’s background service)
    • The daemon pulls the image
    • It creates a container
    • It streams the output to your terminal
  • Create a free Docker Hub account now. You will need it!

A daemon error means the Docker application is not running: Appendix 02

Let’s create our first container

  • File 1, requirements.txt: the packages to install
numpy==2.5.2
pandas==3.0.5
  • File 2, hello.py: the script the container runs
import numpy as np
import pandas as pd

print("Hello, DATASCI350!")
print(f"numpy  {np.__version__}")
print(f"pandas {pd.__version__}")
  • File 3, the Dockerfile, puts them together (next slide)

The Dockerfile

# Start from an official Python image on Docker Hub
FROM python:3.14-slim

# Create /app inside the image and move into it
WORKDIR /app

# Copy requirements.txt from your folder to /app
# First, so editing hello.py won't reinstall
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy hello.py from your folder into /app
COPY hello.py .

# The command that runs when the container starts
CMD ["python", "hello.py"]
  • -r installs from the file, and --no-cache-dir keeps no copy of the downloads
  • Build it: -t tags the image datasci350-example, and . is the folder holding the Dockerfile:
docker build -t datasci350-example .
  • docker build runs the instructions in order. COPY and RUN add layers, while CMD only records the start command
Instruction What it does Runs when
FROM Picks the base image Build
WORKDIR Sets the folder for every later step Build
COPY Brings a file from your folder into the image Build
RUN Executes a command inside the image Build
CMD Names the command the container starts with Start

Official Python image: https://hub.docker.com/_/python

Building the image

docker build -t datasci350-example .

#5 [1/5] FROM docker.io/library/python:3.14-slim
#5 sha256:acd43e9beb 30.21MB / 30.21MB 1.8s done
#5 DONE 2.6s

#7 [2/5] WORKDIR /app
#7 DONE 0.4s

#8 [3/5] COPY requirements.txt .
#8 DONE 0.0s

#9 [4/5] RUN pip install --no-cache-dir -r
    requirements.txt
#9 5.262 Successfully installed numpy-2.5.2
    pandas-3.0.5 [...]
#9 DONE 5.6s

#10 [5/5] COPY hello.py .
#10 DONE 0.0s

#11 exporting to image
#11 DONE 3.2s
  • [1/5] to [5/5] are the instructions before CMD
  • [1/5] downloads the base image: 2.6 seconds, once per machine
  • [4/5] installs the packages: 5.6 seconds
  • The whole build took 13 seconds, most of it downloading
  • docker images shows the result:
docker images datasci350-example

IMAGE                DISK USAGE  CONTENT SIZE
datasci350-example        409MB        88.2MB
  • It holds Debian, Python, NumPy, pandas and your code

Layer caching

  • Rebuild without changing anything:
docker 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
  • Every layer says CACHED, and the build takes 0.79 seconds
  • Docker reuses a layer when its instruction and inputs are unchanged
  • Once one layer misses, every layer below it rebuilds
  • So COPY requirements.txt sits above COPY hello.py. Editing your script rebuilds only the last layer, and pip install stays cached
  • With COPY . . (copy everything) at the top, any edit reinstalls every package
  • The project starter’s Dockerfile uses the same order

Let’s run and share the container

  • docker run starts a container from the image and runs its CMD:
    • --rm deletes the container when it stops
docker run --rm datasci350-example

Hello, DATASCI350!
numpy  2.5.2
pandas 3.0.5
  • These versions come from inside the image, so every machine prints the same

  • You can now hand the image to someone 🤓

  • Log in to Docker Hub:

docker login
  • Tag the image with your own username (the part before the slash):
docker tag datasci350-example \
  danilofreire/datasci350-example:latest
  • Push it:
docker push \
  danilofreire/datasci350-example:latest

bf7af0229701: Pushed
c66215f6ebe7: Pushed
latest: digest: sha256:b24fd8fc20ef...
    size: 856
  • Optional, not needed for the final project: buildx builds for Intel and Apple chips at once, so anyone can pull it
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t danilofreire/datasci350-example:latest \
  --push .

The image on Docker Hub

https://hub.docker.com/r/danilofreire/datasci350-example

Docker pull

  • Anyone can now download the image from Docker Hub with docker pull, then run it:
docker pull danilofreire/datasci350-example:latest

latest: Pulling from danilofreire/datasci350-example
Digest: sha256:0e5a94a5aebd...
Status: Downloaded newer image

docker run --rm danilofreire/datasci350-example:latest

Hello, DATASCI350!
numpy  2.5.2
pandas 3.0.5
  • Python, NumPy and pandas come inside the image, so they only need Docker
  • It runs on Windows, Linux and any Mac, because it is published for amd64 (Intel/AMD) and arm64 (Apple Silicon)
  • Your project works the same way. I build and run it on a clean machine, and if your report appears, we both celebrate 🎉
  • Lecture 25 builds the project container line by line

Try it at home

  1. Copy the docker/ folder from the course repository: https://github.com/danilofreire/datasci350/tree/main/lectures/lecture-23/docker
  2. Open a terminal inside that folder
  3. Run docker build -t datasci350-example .
  4. Run docker run --rm datasci350-example. Three lines appear
  5. Open requirements.txt. Add the line polars==2.1.0
  6. Open hello.py. Import polars and print pl.__version__
  7. Run docker build -t datasci350-example . again
  8. Read the output. Note which steps say CACHED
  9. Run docker run --rm datasci350-example. Four lines now
  10. If you have time, swap the two COPY lines and rebuild

Solution: Appendix 01

Summary

What we learned today

  • Dependency management records what your code needs
  • Code breaks when the environment changes (the Python 2 print script)
  • pip freeze writes == pins, and pip install -r reads them
  • Export conda with --from-history to work on other platforms
  • Commit pyproject.toml and uv.lock, then uv sync rebuilds the environment
  • An image is a template, a container runs it, a registry stores it
  • Layer caching cut a 13-second build to 0.79 seconds
  • Docker Desktop, Podman, Colima and OrbStack run the same commands

Your container is the deliverable: if docker build and docker run show your report on my machine, you’re done 🚀

Next class

  • Quiz 04 (19 November): web APIs and JSON, Lectures 18 and 19
  • Assignment 09 is due the same day
  • Lecture 25 (24 November): the project starter’s Dockerfile, with Python and Quarto
  • Today’s Dockerfile is a small version of it

Before then:

  1. Install Docker Desktop or an alternative, and run docker run hello-world
  2. Create a free Docker Hub account
  3. Clone the project starter and run docker build once on your own wifi

Quiz 05 covers Lectures 21, 22, 23 and 25. The final project is due on the last day of classes

And that’s all for today! 🎉

Appendix 📚

Appendix 01: Exercise solution

Steps 5 and 6, the two edited files:

# requirements.txt
numpy==2.5.2
pandas==3.0.5
polars==2.1.0
# hello.py
import numpy as np
import pandas as pd
import polars as pl

print("Hello, DATASCI350!")
print(f"numpy  {np.__version__}")
print(f"pandas {pd.__version__}")
print(f"polars {pl.__version__}")

Step 9, the run:

docker run --rm datasci350-example

Hello, DATASCI350!
numpy  2.5.2
pandas 3.0.5
polars 2.1.0
  • The image grew from 409MB to 639MB on disk

Steps 7 and 8, the rebuild on my laptop:

#6 [2/5] WORKDIR /app
#6 CACHED

#7 [3/5] COPY requirements.txt .
#7 DONE 0.1s

#8 [4/5] RUN pip install --no-cache-dir -r
    requirements.txt
#8 7.711 Successfully installed numpy-2.5.2
    pandas-3.0.5 polars-2.1.0 [...]
#8 DONE 8.1s

#9 [5/5] COPY hello.py .
#9 DONE 0.0s
  • One layer stayed cached and three rebuilt. The miss at #7 forced every later layer to run again
  • pip install reran in full (8.1 seconds), downloading NumPy and pandas again along with polars
  • Step 10: with the COPY lines swapped, editing hello.py alone invalidates COPY hello.py and re-runs pip install for nothing

Appendix 02: When something goes wrong

Cannot connect to the Docker daemon

Docker Desktop is not running. Start the application, wait for the whale icon to settle, and try again. On my laptop OrbStack was stopped, and docker info answered failed to connect to the docker API at unix://~/.orbstack/run/docker.sock.

permission denied ... /var/run/docker.sock

On Linux, your user is not in the docker group. Run sudo usermod -aG docker $USER, then log out and back in.

pip: command not found

Your virtual environment is not active. Run source .venv/bin/activate and check with which python, which should print a path ending in .venv/bin/python.

No matching distribution found for numpy==2.5.2

That version does not exist for your Python. Check the pin against PyPI, or loosen it to numpy>=2.0.

toomanyrequests: You have reached your pull rate limit

Docker Hub allows 100 anonymous pulls every six hours from one address. Run docker login with your free account (200 pulls) and pull again.

failed to read dockerfile: open Dockerfile: no such file or directory

You are in the wrong folder. The . at the end of docker build -t name . is where Docker looks, so cd into the folder holding the Dockerfile

Appendix 03: Docker on Windows with WSL

With Docker Desktop (recommended)

  1. Install WSL: open PowerShell as administrator, run wsl --install and restart. You get Ubuntu by default
  2. Install Docker Desktop for Windows and keep “Use WSL 2” ticked
  3. In Docker Desktop, open Settings → Resources → WSL Integration, turn on Ubuntu, then Apply & restart
  4. Open Ubuntu and check:
docker run hello-world
  • Keep your projects inside Ubuntu (~/...), not in /mnt/c/.... Builds are much faster there

Without Docker Desktop

Install Docker Engine inside Ubuntu, then let your user run docker without sudo:

curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker $USER

Close and reopen the terminal. If docker cannot connect, start the engine with sudo service docker start. Use one route only, not both.

The command 'docker' could not be found in this WSL 2 distro

WSL Integration is off for your distribution. Turn it on as in step 3