Foundations to Frontier
Tests
C. Programming, Tools and HPC › C4 Linux and Systems

Containers: Docker and Apptainer/Singularity

A container packages a program with its entire user-space environment (libraries, Python, CUDA runtime, configuration) so it runs identically on a laptop, a cloud VM, a cluster or a robot. This topic explains what a container really is (processes isolated by Linux namespaces and limited by cgroups, sharing the host kernel), images built from layers with a content-addressed build cache, writing efficient Dockerfiles (ordering, .dockerignore, multi-stage builds, pinned versions), running with volumes, ports and GPUs, and Apptainer/Singularity, the container runtime of HPC centres (single-file SIF images, no root daemon, runs as you). In the exercises you parse Dockerfiles, compute layer cache keys, simulate builds and an overlay file system with whiteouts; then you replay a project's commit history to measure how Dockerfile ordering, .dockerignore and multi-stage builds change total build time and image size.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Shipping the whole kitchen

“It works on my machine” happens because programs depend on many invisible things: the exact Python version, libraries, system tools. A container packs the program together with everything it needs into one box (an image) that runs the same anywhere. It isn’t a whole virtual computer: it shares the host’s operating-system core, so it starts in a fraction of a second. Images are built in layers, like a stack of transparent sheets, and unchanged layers are reused, which is why the order of building steps matters.

The Docker build cache: what reruns after a change?
Dockerfile:
FROM python:3.12-slimfirst build
COPY . /appfirst build
RUN apt-get install -y build-essentialfirst build
RUN pip install -r requirements.txtfirst build
CMD ["python", "-m", "src.train"]first build
build context sent: 5.0 GB
this build: —
0 rebuilds, total 0.0 min
Blue = reused from cache, orange = rebuilt. With the naive order, any edit (even new log files in the context) changes the COPY . layer and forces the slow apt and pip steps to rerun. Copying requirements.txt first means pip reruns only when dependencies change, and .dockerignore stops gigabytes of data and logs from being sent and copied on every build.
Why engineers care

Reproducing a published result, moving a simulation from a laptop to a supercomputer, and deploying the same perception stack to every robot in a fleet all rely on containers. Space agencies and research labs ship analysis pipelines and ground-segment services as container images so that an environment validated once is the one that runs.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A container image contains…
  2. 2. Why are containers faster to start than virtual machines?
  3. 3. In the demo with the naive order, editing one source file…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Images and containers

FROM python:3.12-slim                         # base image (pin a digest for full reproducibility)
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends libhdf5-dev \
    && rm -rf /var/lib/apt/lists/*            # one layer: install and clean up together
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY src/ ./src/
CMD ["python", "-m", "src.train"]             # exec form: your process is PID 1 and receives signals
docker build -t trainer:1.0 .
docker run --rm -it -v "$PWD/data:/app/data" -p 6006:6006 --gpus all trainer:1.0
docker push registry.example.org/lab/trainer:1.0

An image is a read-only stack of layers plus metadata; a container is a running (or stopped) instance with a thin writable layer on top, which disappears with --rm. Persist data with volumes or bind mounts (-v host:container), never inside the container. Registries (Docker Hub, GitHub Container Registry, a lab registry) store images by name and tag, and immutably by digest (image@sha256:…).

📝 Quick check (Level 1)
0/3 answered
  1. 1. Where should a container write results you want to keep?
  2. 2. -p 6006:6006 does what?
  3. 3. An image tag like :latest is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

What a container is, in kernel terms

A container is an ordinary process tree that the kernel isolates with namespaces (its own view of process IDs, mount points, network, hostname, users) and limits with cgroups (CPU, memory, I/O; exceeding the memory limit triggers the OOM killer, C4.3). Its root file system is an overlay of the image layers: lookups go from the top layer down, and deleting a lower-layer file writes a “whiteout” marker in the upper layer. Because the kernel is shared, a container cannot change kernel versions or load drivers; GPU access works by mounting the host’s driver libraries into the container (NVIDIA Container Toolkit, --gpus all).

The build cache

Each instruction produces a layer identified by a cache key that depends on the parent layer, the instruction text, and, for COPY/ADD, a checksum of the copied files. At the first changed key, that layer and every one after it are rebuilt. Consequences:

  • Order instructions from rarely changing (system packages) to often changing (your code).
  • Copy dependency manifests (requirements.txt, pyproject.toml, lock files) before the source.
  • Use .dockerignore to keep data, logs, .git and virtual environments out of the build context.
  • RUN apt-get update alone is cached forever on its text: combine update and install in one RUN.
  • Multi-stage builds compile in a large builder image and copy only the results into a slim runtime image.
🐍 Exercise 1: Dockerfiles, cache keys and overlays
Parse a Dockerfile (comments, backslash continuations, ARG/ENV substitution), turn CMD into argv (exec versus shell form), select files for COPY sources with ignore patterns, compute layer cache keys from the parent key, instruction and copied file contents, simulate builds with a persistent cache and step costs, and implement overlay lookups with whiteout files.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Containers isolate processes using…
  2. 2. Why COPY requirements.txt before COPY . ?
  3. 3. A whiteout file in an upper layer…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Apptainer / Singularity on HPC

Shared clusters rarely allow Docker: its daemon runs as root, and a user in the docker group can effectively become root. Apptainer (formerly Singularity) is designed for them:

  • An image is a single read-only file (SIF, a compressed squashfs), easy to copy to scratch and cheap for a parallel file system to serve (one large file instead of thousands, C4.1).
  • No daemon; the container runs as your own user, with your home directory and the current directory mounted by default.
  • Converts Docker images: apptainer build trainer.sif docker://registry.example.org/lab/trainer:1.0.
  • apptainer exec --nv trainer.sif python -m src.train exposes the GPUs; MPI jobs use the host’s MPI and interconnect.

Reproducibility and security

Pin base images by digest and dependencies by lock file; record the image digest with every result (C2.4). Run as a non-root USER, avoid --privileged, keep secrets out of layers (they persist in history even if deleted later), and scan images for vulnerable packages. For robots and edge devices, build multi-architecture images (linux/amd64, linux/arm64) with docker buildx.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Why do HPC centres prefer Apptainer over Docker?
  2. 2. A secret copied in one layer and deleted in a later layer…
  3. 3. A SIF image is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Containers, measured

Exercise 1. The parser joins continuations and substitutes ARG PY=3.12 into FROM python:${PY}-slim. With step costs of 60 s (apt-get) and 180 s (pip), the first build takes 241 s; editing src/train.py reruns only the last COPY (0.5 s); editing requirements.txt reruns pip but not apt-get (181 s); rebuilding identical inputs gives the identical image ID. In the overlay, an upper layer’s /etc/os-release shadows the base and /tmp/.wh.build.log hides the base’s log.

Exercise 2: Dockerfile choices over a commit history. 60 commits: code changes in every commit, requirements.txt in 3 of them, logs and .git grow every commit, a 5 GB data file sits in the project folder. Costs: apt-get 60 s, pip 180 s, sending the build context at 200 MB/s, copying it at 400 MB/s.

Dockerfile total for 59 rebuilds pip installs
naive (COPY . first) 275 min 59
dependencies first 48 min 3
dependencies first + .dockerignore 9 min 3

Reordering cuts the pip reruns to the 3 genuine dependency changes; the remaining 39 minutes come from sending and copying 5.3 GB of data, logs and .git on every build, which .dockerignore removes. Image size (illustrative layer sizes): 6.7 GB naive (data and logs baked in), 1.38 GB with .dockerignore, 1.09 GB with a multi-stage build that leaves compilers and headers behind.

🐍 Exercise 2 (research): Dockerfile choices over a commit history
Using a compact build-cache model, replay 60 commits of a project (code edits, occasional dependency changes, growing logs, a large data file) through three Dockerfiles: naive order, dependencies first, and dependencies first with .dockerignore. Measure total rebuild time and pip reruns, and compare final image sizes including a multi-stage build.

Containers in AI, robotics and aerospace

  • HPC: Apptainer images of simulation and training stacks, with --nv for GPUs and host MPI for multi-node jobs.
  • ML deployment: inference servers (Triton, TorchServe) shipped as images; the same image in CI and production.
  • Robotics: ROS 2 workspaces in containers, cross-built for arm64 robot computers, updated fleet-wide by pulling a new digest.
  • Ground segments: mission-control and data-processing services orchestrated as containers (Kubernetes), with images pinned and scanned for flight-heritage configuration control.

References

  1. D. Merkel (2014). “Docker: lightweight Linux containers for consistent development and deployment.” Linux Journal, 239.
  2. G. M. Kurtzer, V. Sochat, M. W. Bauer (2017). “Singularity: scientific containers for mobility of compute.” PLOS ONE, 12(5).
  3. Docker documentation (docs.docker.com): Dockerfile reference, Build cache, Multi-stage builds.
  4. Apptainer User Guide (apptainer.org/docs).
  5. Linux manual pages: namespaces(7), cgroups(7); Open Container Initiative image specification (opencontainers.org).