Docker & Containerization#
This guide is a practical, end-to-end reference for containerizing research and
machine-learning code with Docker and running it anywhere — your laptop, CI, a shared
GPU cluster, or another HPC system. It is written for researchers, students, and
engineers who have working code and now need it to run identically somewhere else, without
the familiar “but it works on my machine” failure.
The emphasis throughout is on building an accurate mental model first — images versus containers, layers, the engine, registries — and then layering the commands on top of it. Most confusion with Docker comes not from the commands but from not picturing what an image is and what a container actually does when it starts.
Tip
You do not have to read this top to bottom. Use the section headers (and the “On this page” list below) to jump straight to what you need — building an image, pushing to a registry, or running on an HPC cluster — and skip anything you already know.
Scope. This guide covers building, running, sharing, and deploying container images. It assumes ordinary familiarity with a terminal and with Git. Containers are the fourth pillar of a shared codebase, after Git & GitHub, testing, and CI/CD: they take the code that passed your tests in CI and turn it into a single artifact that runs the same way everywhere.
Note
Hands-on practices are marked throughout with a Practice callout, and a dedicated Hands-On Exercises section at the end ties them together into short labs. You only need a container engine (Docker or Podman) and a terminal to follow along. Every command here operates on a tiny throwaway service and touches nothing else on your machine.
Why Containers#
Research and machine-learning work is only useful if its results are trustworthy and reproducible. Yet the moment code leaves the machine it was written on, reproducibility starts to leak away: a slightly different Python version here, an unpinned library there, a missing system package on the server, and the run that worked yesterday fails today.
Before containers, “shipping software” meant shipping instructions: install Python 3.11, these 40 libraries at these exact versions, this system library, set these environment variables, and hope the target machine matches. Every difference between your machine and the server is a chance for a silent failure.
A container ships the result instead: your code and its entire userspace environment — interpreter, libraries, system packages, files — bundled as one immutable image. The only thing it borrows from the host is the Linux kernel. The one-sentence promise is that “it works on my machine” becomes “it works in this image — here is the image.”
Concern |
Virtual Machine |
Container |
|---|---|---|
Boots a full guest OS |
Yes |
No — shares the host kernel |
Isolation |
Strong (hardware-level) |
Process-level |
Startup |
Slow |
Fast |
Density |
Few per host |
Many per host |
Right tool for |
A different OS; strict user isolation |
Packaging & shipping an app reproducibly |
For an ML or engineering team the payoff is concrete: the image that passed CI is byte-for-byte the image that runs on the cluster. No drift, no “works on my machine.”
How Containers Work (a Brief Look Inside)#
Three nouns do most of the work. Get these right and the commands stop feeling arbitrary.
Image, Container, Registry#
Term |
What it is |
|---|---|
Image |
A read-only template: a stack of filesystem layers plus metadata (the default command, environment, exposed ports). Think of it as a class. |
Container |
A running (or stopped) instance of an image, with a thin writable layer on top. Think of it as an object. Many containers can come from one image. |
Registry |
A server that stores images so others — and your HPC cluster — can pull them. Docker Hub and ghcr.io are registries. |
Docker is a popular image and containerization platform.
A Dockerfile builds an image; that image runs as one or more containers, and
is pushed to a registry so any other host can pull and run the exact same image.#
Layers and the Build Cache#
An image is built in layers — one per line in the Dockerfile. Each layer is
cached and content-addressed. If a layer’s inputs have not changed, Docker reuses the cache
instead of rebuilding, which is what makes an unchanged rebuild finish in a second or two.
You can think of each consecutive line in the Dockerfile as a stack. First is the FROM base image,
then typically apt-get or pip or uv installs, then source code updates. Each line adds a layer that then gets cached
for subsequent builds. If you want to change any given layer in the stack, you can reuse the cache from all layers
below it, but you will have to rebuild everything from that layer up (which then gets recached). Therefore, the order
of how you create your Dockerfile image matters! Think about what you’re going to be changing most frequently
(like source code as you’re developing) and place it at the tail of the file. This keeps image rebuilds speedy.#
The Engine#
docker (the CLI) talks to a background engine (daemon) that actually builds images
and runs containers. On a Mac or Windows host, that Linux kernel lives inside a tiny VM that Docker Desktop
manages for you; on Linux it is your own kernel directly.
Tip
Hold on to one idea above all: an image is an immutable template; a container is a process. Almost every surprising Docker behaviour follows from that single distinction.
Prerequisites#
You need one container engine installed to follow the local demos. Any one of these works — the commands are nearly identical:
Docker Desktop (macOS/Windows) or Docker Engine (Linux) — the default in this guide.
Podman — rootless, daemonless, and a drop-in replacement.
alias docker=podmanand most commands below just work (see Podman — the Rootless, Daemonless Drop-in).
Verify what you have:
docker --version # or: podman --version
docker compose version # the Compose plugin (optional but used later)
Note
If nothing is installed you can still read along and write every file in this guide; only
the docker build / docker run steps need an engine to talk to.
A Scratch Service to Containerize#
We will containerize a tiny but realistic service: a FastAPI app that loads a stand-in “model” and exposes a prediction endpoint. It is small enough to reason about and real enough that every concept here applies unchanged to your actual projects.
Create a scratch directory and add the app (app.py):
"""A tiny FastAPI service with a stand-in 'model'. Nothing here is Docker-specific —
that is the point: ordinary code becomes portable once it is containerized."""
import os
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="amii-container-demo")
# A stand-in for a trained model artifact: weights we would normally load from disk.
WEIGHTS = {"intercept": 1.5, "slope": 2.0}
GREETING = os.environ.get("GREETING", "hello from the container")
class Point(BaseModel):
x: float
@app.get("/")
def root():
return {"message": GREETING, "hostname": os.uname().nodename}
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/predict")
def predict(p: Point):
y = WEIGHTS["intercept"] + WEIGHTS["slope"] * p.x
return {"x": p.x, "y_pred": y}
Pin the dependencies exactly in requirements.txt:
fastapi==0.115.0
uvicorn[standard]==0.30.6
pydantic==2.9.2
Important
Notice the exact versions. Reproducibility is the whole reason we are here — an
unpinned fastapi would let the image drift over time and quietly break. Pin everything
that goes into an image, base image included.
The Dockerfile — a Recipe for the Image#
A Dockerfile is an ordered list of instructions; each one produces a layer. Here is the
whole thing — we read it line by line below.
# 1. Start from a small, official, *pinned* base image.
FROM python:3.11-slim
# 2. Everything below happens inside this directory in the image.
WORKDIR /app
# 3. Copy ONLY the dependency manifest first, then install.
# This layer is cached and reused on every build where requirements.txt
# is unchanged — so editing app.py does NOT reinstall your dependencies.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 4. Now copy the source. This layer changes on nearly every commit,
# so it sits AFTER the expensive install to preserve the cache.
COPY app.py .
# 5. Document the port the app listens on (does not publish it by itself).
EXPOSE 8000
# 6. Run as a non-root user — a container should not run as root by default.
RUN useradd --create-home appuser
USER appuser
# 7. The default process for a container started from this image.
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
Reading the Dockerfile#
FROM python:3.11-slim— every image starts from another image. Note that this base image could also be one of your images.-slimindicates a trimmed down image size with less bloat. Take note of the pinned the tag which avoids usinglatest.WORKDIR /app— sets (and creates) the working directory for later instructions and at runtime.COPY requirements.txt .thenRUN pip install— before copying source. This is the single most important caching trick: dependency installs are slow and rarely change, so give them their own early layer. Source changes then rebuild only the fast final layers.EXPOSE 8000— documentation/metadata. You still publish the port at run time with-p.USER appuser— drop root. If the container is ever compromised, the process is not root inside it.CMD [...]— the default command the container runs when it starts.0.0.0.0(not127.0.0.1) is essential: the app must listen on all interfaces to be reachable from outside the container.
Why We Need CMD — a Container is Its Main Process#
This is the part that trips people up, so it is worth stating plainly: a container is not a
virtual machine that boots up and waits for you to log in. A container is a single
process. When that process exits, the container stops. The image must therefore declare
what that one process is — that is what CMD does.
Without a CMD the container would have nothing to run and would exit immediately. With
it, docker run amii-container-demo:0.1 needs no extra arguments. A few consequences are
worth internalising:
The command must run in the foreground.
uvicorn ...(no&, no daemonising) blocks and keeps serving, which is what you likely want. If you background your server and theCMDreturns, the container dies instantly, even though “the server started.”CMD is only the default — it is easily overridden. Anything after the image name on
docker runreplaces it:docker run amii-container-demo:0.1 python -c "print(1+1)"runs that instead. Handy for one-off tasks against the same image.CMD vs RUN — do not confuse them.
RUNexecutes at build time to create a layer (e.g.pip install).CMDexecutes at run time and just records the default process.CMD vs ENTRYPOINT —
ENTRYPOINTsets a fixed executable that always runs;CMDsupplies default arguments to it (or the whole default command when there is noENTRYPOINT). For a single app,CMDalone is the simplest choice.
Note
Because a container dies when its main process exits, a container that is not meant to
run a long-lived service — a dev box you just want to exec into — needs a command that
deliberately never returns. That is exactly the tail -f /dev/null trick in
Local Development — Edit in Your IDE, Run in the Container.
.dockerignore — Keep Junk Out of the Build#
Just like .gitignore, a .dockerignore keeps files out of the build context sent to
the engine. This makes builds faster and images cleaner, and avoids accidentally baking
secrets or huge data files into an image. Remember that eventually this image might be served
in production as a container, so the smaller the image, the less data needs to be pulled to
spawn it.
__pycache__/
*.pyc
.venv/
.git/
.gitignore
.env
*.md
data/
*.ipynb_checkpoints
Building the Image#
docker build reads the Dockerfile, executes each instruction, and produces a tagged
image. -t names it name:tag; the trailing . is the build context (the current
directory).
docker build -t amii-container-demo:0.1 .
Watch the output: the first build runs every step; a second build (after editing only
app.py) reuses the cached dependency layer and finishes in a second or two. Inspect what
you built:
docker images amii-container-demo # the image, its tag, and size
docker history amii-container-demo:0.1 # the layers, newest first
Practice — build your first image
Create the scratch folder, and add
app.py,requirements.txt, and theDockerfileabove.Run
docker build -t amii-container-demo:0.1 .and watch each layer build.Edit a string in
app.py, rebuild, and confirm thepip installlayer is served from cache (CACHEDin the output) while only the source layer rebuilds.
Running the Container#
docker run creates a container from the image and starts its CMD. The flags that
matter most:
Flag |
What it does |
|---|---|
|
Publish a container port → host port ( |
|
Set an environment variable, overriding the image default. Configuration comes from the environment, never hard-coded. |
|
Delete the container when it exits (no clutter). |
|
Detached — run in the background. |
|
Give the container a friendly handle to refer to later. |
Run the service in the background, then call it from the host:
docker run -d --rm --name demo -p 8000:8000 -e GREETING="hello from Docker" \
amii-container-demo:0.1
curl -s http://localhost:8000/ # {"message": "hello from Docker", ...}
curl -s http://localhost:8000/health # {"status": "ok"}
curl -s -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" -d '{"x": 3}' # {"x": 3, "y_pred": 7.5}
Observe, Inspect, and Clean Up#
The day-to-day commands you will reach for constantly:
docker ps # running containers
docker logs demo # stdout/stderr of the container
docker exec demo ls -la /app # run a command inside the running container
docker exec -it demo /bin/bash # drop into an interactive (-it) terminal within the container
docker stop demo # stop it (started with --rm, so it is also removed)
The Container Lifecycle#
A container moves from created to running to stopped; a stopped container still
exists (and takes disk) until you docker rm it.#
docker ps -a shows stopped containers too; docker system prune reclaims space from
stopped containers, dangling images, and unused networks.
Data That Outlives the Container — Volumes#
A container’s writable layer is ephemeral: docker rm and it is gone. To be really clear,
if you stop a container from running and respawn the container, your changes within your environment
will not persist. E.g., you apt-get install wget to grab a file, then the container dies, and you
respawn it: wget will no longer be available because it wasn’t baked into the original image.
For anything you need to keep — a database, model checkpoints, outputs — mount storage from outside the
container:
Bind mount —
-v "$(pwd)/data":/app/datamaps a host directory into the container. Great for development (edit on the host, see it inside instantly) and for reading datasets or writing results.Named volume —
-v mydata:/app/datais a volume managed by Docker. Better for production state.
# Mount a host folder for outputs:
docker run --rm -p 8000:8000 \
-v "$(pwd)/data":/app/data \
amii-container-demo:0.1
Important
Rule of thumb: code goes in the image; data and secrets come in at runtime (volumes
and -e / --env-file), never baked into the image.
Closing the Loop — Build & Push from GitHub Actions#
If CI already runs your tests on every PR, the natural next step is: when a change lands on
main, have CI build the image and push it to your image registry automatically, so a fresh,
tested image is always waiting for the cluster to pull. No manual docker build on anyone’s
laptop.
The full chain: commit → PR → tests (CI) → merge → image built & pushed → pull & run on the cluster.#
Drop this reference workflow in .github/workflows/docker-publish.yml:
name: Build and publish image
on:
push:
branches: [main]
tags: ['v*']
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # allow pushing to ghcr.io
steps:
- uses: actions/checkout@v4
- name: Log in to ghcr.io
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }} # provided automatically
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
file: ./Dockerfile
push: true
tags: |
ghcr.io/amii-engineering/amii-container-demo:latest
ghcr.io/amii-engineering/amii-container-demo:${{ github.sha }}
Local Development — Edit in Your IDE, Run in the Container#
Everything so far rebuilds the image to see a change. That is correct for shipping, but painful while you are actively coding: edit → rebuild → run, for every small change.
The development pattern fixes this with a bind-mounted source volume: mount your project
directory from the host into the container so the code the container runs is the code
you are editing. Save a file in VS Code / PyCharm and the change is already inside the
container — no rebuild. Pair it with a hot-reloading server (uvicorn --reload) and the app
restarts itself on save.
With a bind mount, your editor writes to the host directory and the container sees the change instantly — no rebuild for source edits.#
What you changed |
What to do |
|---|---|
Source ( |
The volume syncs it instantly; |
Dependencies or the |
The image itself is stale. Rebuild it with |
A development-specific Compose file (docker-compose.dev.yml) mounts the code, forces a
reload server, and is meant to be run with --build:
# Run with: docker compose -f docker-compose.dev.yml up --build
services:
api:
build:
context: .
dockerfile: Dockerfile # rebuilt whenever you pass --build
volumes:
- ./:/app # sync the WHOLE project into the container
- /app/__pycache__ # keep container-managed paths from the host mount
ports:
- "8000:8000"
environment:
GREETING: "hello from dev mode"
PYTHONUNBUFFERED: "1"
# Override the image CMD with a hot-reloading server for development:
command: uvicorn app:app --host 0.0.0.0 --port 8000 --reload
Get a Shell Inside a Running Container#
To poke around inside a running container — check files, run a one-off command, debug an import — open an interactive shell in it:
docker exec -it <container_name> /bin/bash # or /bin/sh on minimal images
-it = interactive + TTY. Find <container_name> with docker ps. This is the single
most useful debugging command day to day: you are now inside the container’s filesystem and
environment.
Keeping a “Dev Box” Alive — the tail -f /dev/null Trick#
As Why We Need CMD — a Container is Its Main Process explained, a container lives exactly as long as its main process. If
that process is not a long-running service — say you just want a container to exec into —
it will start and immediately exit, with nothing to attach to. Give it a command that never
returns:
CMD ["tail", "-f", "/dev/null"]
tail -f /dev/null blocks forever using no CPU. The container stays alive, and you
docker exec -it <name> /bin/bash into it whenever you like — a persistent, disposable
Linux box with your project mounted.
More Than One Container — Docker Compose#
Real services rarely run alone: an API plus a database plus a cache. Compose declares a
multi-container setup in one docker-compose.yml and runs it with a single command. Here
our API gets a companion Redis, wired together on a private network Compose creates
automatically:
services:
api:
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
GREETING: "hello from compose"
depends_on:
- redis
redis:
image: redis:7-alpine
# No ports published: only the api container can reach it, by the name "redis".
docker compose up --build # start everything, stream logs
docker compose ps # what is running
docker compose down # stop and remove the stack
Inside the api container, the database is reachable simply as the hostname redis —
Compose’s built-in DNS resolves service names on the shared network.
Stop Memorising Flags — Wrap Them in Make or just#
docker run -d --rm --name demo -p 8000:8000 -e GREETING=... image:tag is a lot to retype
correctly. Teams put these commands behind short, memorable targets so everyone runs them the
same way, and new teammates read the file to learn the project’s workflow.
Make ships on virtually every Unix machine. One gotcha: recipe lines must be indented with a real TAB, not spaces.
IMAGE := amii-container-demo
TAG := 0.1
NAME := demo
build: ## Build the image
docker build -t $(IMAGE):$(TAG) .
start: ## Run the container in the background
docker run -d --rm --name $(NAME) -p 8000:8000 -e GREETING="hi" $(IMAGE):$(TAG)
stop: ## Stop (and, via --rm, remove) the container
docker stop $(NAME)
shell: ## Open an interactive shell inside the running container
docker exec -it $(NAME) /bin/bash
.PHONY: build start stop shell
just is a modern, purpose-built command runner: no tab
pitfalls, a built-in --list, easy recipe arguments, and .env support. Same idea,
friendlier file (a justfile):
image := "amii-container-demo"
tag := "0.1"
name := "demo"
# Build the image
build:
docker build -t {{image}}:{{tag}} .
# Run the container in the background
start:
docker run -d --rm --name {{name}} -p 8000:8000 -e GREETING="hi" {{image}}:{{tag}}
# Shell into the running container
shell:
docker exec -it {{name}} /bin/bash
Either way, the payoff is the same: the correct, project-specific commands live in version control, so nobody has to remember flags and everyone runs the container identically.
Podman — the Rootless, Daemonless Drop-in#
Podman runs the same OCI images with a nearly identical CLI, but with two differences that matter on shared servers:
Daemonless — no background root daemon; each command is a normal process.
Rootless by default — containers run as your user, not root. On multi-user machines like a shared HPC cluster, this is often the only engine allowed, because a rootful Docker daemon effectively grants root on the host.
The commands you already learned transfer directly:
podman build -t amii-container-demo:0.1 .
podman run -d --rm -p 8000:8000 amii-container-demo:0.1
podman ps
podman login ghcr.io -u <GITHUB_USER>
podman push ghcr.io/amii-engineering/amii-container-demo:0.1
alias docker=podman # most scripts then work unchanged
If Podman is your cluster’s engine, everything above in this guide applies as-is; just swap the command name.
Apptainer / Singularity — the HPC Runtime#
Many research and HPC clusters do not allow Docker at all (that root daemon again). Instead they use Apptainer (formerly Singularity), built for shared, multi-user, GPU compute:
Runs as your user — no root, safe on shared nodes.
An image is a single ``.sif`` file you can copy around like any file — no daemon, no local registry.
Pulls directly from Docker/ghcr registries and converts to
.sif— so the image you built and pushed above works here unchanged.The host filesystem (home, project, scratch) is mounted by default, which fits HPC data layouts.
# Pull your pushed image and convert it to a .sif file:
apptainer pull demo.sif docker://ghcr.io/amii-engineering/amii-container-demo:0.1
apptainer run demo.sif # run the image's default command
apptainer exec demo.sif uvicorn app:app --host 0.0.0.0 --port 8000 # a specific command
# GPU passthrough (NVIDIA) — the killer feature on compute nodes:
apptainer exec --nv demo.sif python -c "import os; print('gpu-ready')"
# Bind a host directory (data / outputs) into the container:
apptainer exec --bind /project/data:/app/data demo.sif ls /app/data
Important
Key mental-model shift from Docker: there is no daemon and no -d / docker ps.
An Apptainer container is just a process you started — it lives and dies with your shell
or your Slurm job. Ports are not “published”; the process shares the host network directly.
Running on an HPC Cluster#
Note
Placeholders: the exact hostname, scheduler, partition, and paths on your HPC
cluster are site-specific. Confirm them with your cluster’s HPC support team and replace every
<PLACEHOLDER> below. The workflow is the same everywhere: get on the node → pull the
image → run it (with GPUs) → get your results back.
On a shared HPC cluster, Podman is a common choice. It is the right fit for a multi-user server — rootless and daemonless — while accepting the exact same OCI image you built and pushed earlier, with the commands you already know from Docker.
Step 1 — Get on the server#
ssh <USERNAME>@<HPC_HOSTNAME> # confirm the real host with your HPC support team
Step 2 — Pull the image with Podman#
# Public image:
podman pull ghcr.io/amii-engineering/amii-container-demo:0.1
# Private image — log in first with a token (ghcr.io or Docker Hub):
echo "$GITHUB_TOKEN" | podman login ghcr.io -u <GITHUB_USER> --password-stdin
podman pull ghcr.io/amii-engineering/amii-container-demo:0.1
Step 3a — Run directly on a node (interactive)#
Use this when you have an interactive shell on a compute node and just want to run something now:
podman run --rm --device nvidia.com/gpu=all \
-v /project/<GROUP>/data:/app/data \
ghcr.io/amii-engineering/amii-container-demo:0.1 python your_script.py
Note
GPU flag: rootless Podman uses the CDI interface for GPUs —
--device nvidia.com/gpu=all (requires the NVIDIA Container Toolkit / CDI configured on
the cluster). Some setups still accept --gpus all. Confirm which one your cluster expects.
Step 3b — Submit as a Slurm batch job#
If your cluster uses a scheduler (Slurm is the common one), you do not run on the login node — you
submit a job and it lands on a GPU node. Save this as run_demo.slurm:
#!/bin/bash
#SBATCH --job-name=amii-demo
#SBATCH --partition=<GPU_PARTITION> # confirm partition name
#SBATCH --gres=gpu:1 # request 1 GPU
#SBATCH --cpus-per-task=4
#SBATCH --mem=16G
#SBATCH --time=00:30:00
#SBATCH --output=demo-%j.log # %j = job id
# Run the container on the allocated GPU node with Podman:
podman run --rm --device nvidia.com/gpu=all \
-v /project/<GROUP>/data:/app/data \
ghcr.io/amii-engineering/amii-container-demo:0.1 python your_script.py
sbatch run_demo.slurm # queue the job
squeue -u $USER # your jobs and their state
cat demo-<JOBID>.log # output once it runs
scancel <JOBID> # cancel if needed
Important
Long-running services vs. batch jobs. The FastAPI demo is a service (it stays up and listens on a port). On a cluster that pattern is unusual — clusters are built for batch jobs that start, compute, write results, and exit. For cluster work, override the default command so the container runs your script and exits (as shown above) rather than serving a port forever.
Getting results back#
Results should be written to a bind-mounted host path (/project/.../data, scratch, or
your home), not into the container’s ephemeral layer. Then copy them to your laptop:
scp <USERNAME>@<HPC_HOSTNAME>:/project/<GROUP>/data/results.csv .
Best Practices#
Pin everything — base image tag (
python:3.11-slim, notlatest) and every dependency version. Reproducibility is the whole point.Order layers by change frequency — dependencies before source, so edits do not trigger slow reinstalls.
Keep images small —
-slim/alpinebases and a good.dockerignore. Smaller = faster pulls to the cluster and a smaller attack surface.Never bake in secrets or data — pass them at runtime (
-e,--env-file, volumes). A secret in an image layer is there forever, even if a later layer “deletes” it.Run as non-root — a
USERline is cheap insurance.One concern per image — API in one, database in another; wire them with Compose or the cluster.
Tag with the commit SHA — an image should trace back to the exact code that built it, just like a Git tag pins the code behind a result.
Let CI build the image — humans build images inconsistently; a pipeline builds them the same way every time.
Match the engine to the host — Docker on your laptop and in CI, but Apptainer/Podman on shared GPU clusters. The image is the same; only the run command changes.
Tip
The through-line across the four pillars: Git captures the code, tests prove it works, CI/CD runs those proofs automatically, and containers ship the proven code as one artifact that runs identically everywhere — including HPC clusters.
Hands-On Exercises#
Work through these in order; together they exercise the full workflow.
Lab 1 — Build and run
Create the scratch service (app.py, requirements.txt, Dockerfile), build
amii-container-demo:0.1, run it detached with a published port, and call all three
endpoints with curl. Then docker logs and docker exec into it before stopping
it.
Lab 2 — Caching and slimming
Edit only app.py and rebuild — confirm the pip install layer is CACHED. Then
add a .dockerignore and compare the build-context size reported at the start of the
build.
Lab 3 — Compose and dev mode
Bring up the API + Redis stack with docker compose up --build. Separately, run the
docker-compose.dev.yml dev environment, edit app.py while it runs, and watch
uvicorn --reload restart the app with no rebuild.
Lab 4 — Push and pull
Tag the image for ghcr.io and push it (private by default). From another machine — or with
Apptainer — pull it back and run it. Bonus: add the GitHub Actions workflow and let CI
build and push the image on a merge to main.
Quick Reference#
Command |
Purpose |
|---|---|
|
Build an image from the |
|
List images / show an image’s layers. |
|
Run a container: detached, auto-removed, port published, named. |
|
List running / all (including stopped) containers. |
|
View logs / open a shell inside a running container. |
|
Stop a container / remove a stopped one. |
|
Name an image for a registry / upload it. |
|
Download an image from a registry. |
|
Start / stop a multi-container stack. |
|
Reclaim space from stopped containers, dangling images, unused networks. |
|
Convert a registry image to a |
|
Run rootless with GPUs (on an HPC cluster). |
Further Resources#
Docker documentation — the canonical reference for the CLI, Dockerfile, and Compose.
Dockerfile best practices — layer ordering, small images, and caching in depth.
Podman — the rootless, daemonless engine common on HPC clusters.
Apptainer — the HPC container runtime (formerly Singularity).
GitHub Container Registry docs — ghcr.io, tokens, and package visibility.
Docker Compose — declaring and running multi-container applications.