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 :doc:`Git & GitHub </git_and_github/git_and_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
   :ref:`container-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.

.. contents:: On this page
   :local:
   :depth: 2


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."*

.. list-table::
   :widths: 30 35 35
   :header-rows: 1

   * - 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
^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. list-table::
   :widths: 22 78
   :header-rows: 1

   * - 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.

.. figure:: images/02_build_run_registry.svg
   :width: 720px
   :align: center
   :alt: A Dockerfile builds an image; the image runs as containers and is pushed to a registry.

   `Docker <https://www.docker.com>`__ 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.

.. figure:: images/03_layers_cache.svg
   :width: 720px
   :align: center
   :alt: Each Dockerfile instruction is a cached layer; unchanged layers are reused.

   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=podman`` and
  most commands below just work (see :ref:`container-podman`).

Verify what you have:

.. code-block:: bash

   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 <https://fastapi.tiangolo.com>`_
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``):

.. code-block:: python

   """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``:

.. code-block:: text

   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.

.. code-block:: dockerfile

   # 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. ``-slim`` indicates a trimmed down image size with less bloat.
  Take note of the pinned the tag which avoids using ``latest``.
* ``WORKDIR /app`` — sets (and creates) the working directory for later instructions and
  at runtime.
* ``COPY requirements.txt .`` then ``RUN 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`` (not
  ``127.0.0.1``) is essential: the app must listen on all interfaces to be reachable from
  *outside* the container.

.. _container-cmd:

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
  the ``CMD`` returns, 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 run`` replaces 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. ``RUN`` executes at **build time** to *create
  a layer* (e.g. ``pip install``). ``CMD`` executes at **run time** and just records the
  default process.
* **CMD vs ENTRYPOINT** — ``ENTRYPOINT`` sets a fixed executable that always runs;
  ``CMD`` supplies default *arguments* to it (or the whole default command when there is no
  ``ENTRYPOINT``). For a single app, ``CMD`` alone 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
   :ref:`container-local-dev`.

``.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.

.. code-block:: text

   __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).

.. code-block:: bash

   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:

.. code-block:: bash

   docker images amii-container-demo    # the image, its tag, and size
   docker history amii-container-demo:0.1   # the layers, newest first

.. admonition:: Practice — build your first image
   :class: tip

   #. Create the scratch folder, and add ``app.py``, ``requirements.txt``, and the
      ``Dockerfile`` above.
   #. Run ``docker build -t amii-container-demo:0.1 .`` and watch each layer build.
   #. Edit a string in ``app.py``, rebuild, and confirm the ``pip install`` layer is served
      from cache (``CACHED`` in 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:

.. list-table::
   :widths: 24 76
   :header-rows: 1

   * - Flag
     - What it does
   * - ``-p 8000:8000``
     - Publish a container port → host port (``host:container``). Without this the app is
       unreachable from your machine.
   * - ``-e GREETING=...``
     - Set an environment variable, overriding the image default. Configuration comes from
       the environment, never hard-coded.
   * - ``--rm``
     - Delete the container when it exits (no clutter).
   * - ``-d``
     - Detached — run in the background.
   * - ``--name demo``
     - Give the container a friendly handle to refer to later.

Run the service in the background, then call it from the host:

.. code-block:: bash

   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:

.. code-block:: bash

   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
^^^^^^^^^^^^^^^^^^^^^^^^

.. figure:: images/04_lifecycle.svg
   :width: 720px
   :align: center
   :alt: Container states: created, running, stopped, removed.

   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/data`` maps 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/data`` is a volume managed by Docker. Better for
  production state.

.. code-block:: bash

   # 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.


.. _container-registries:

Registries — Share the Image (and Keep It Private When It Must Be)
------------------------------------------------------------------

To run your image on an HPC cluster, in the cloud, or on a client's infrastructure, you push it to a
**registry** and pull it there. There are many; the commands are the same everywhere —
``login``, ``tag``, ``push``, ``pull``. What differs is the **address format** and, crucially,
the **default visibility**.

An image can leak proprietary code, data paths, or secrets. Some registries publish images
**publicly by default**; others are **private by default**. Pushing to the wrong one is how
private code ends up world-readable.

.. list-table::
   :widths: 24 30 26 20
   :header-rows: 1

   * - Registry
     - Address format
     - Default visibility
     - Log in with
   * - **Docker Hub**
     - ``docker.io/<user>/<repo>``
     - **Public** ⚠️
     - ``docker login``
   * - **GitHub Container Registry** (ghcr.io)
     - ``ghcr.io/<org>/<repo>``
     - **Private**
     - token → ``docker login ghcr.io``
   * - **Google Artifact Registry**
     - ``<region>-docker.pkg.dev/<project>/<repo>/<image>``
     - **Private** (IAM)
     - ``gcloud auth configure-docker``
   * - **Azure Container Registry**
     - ``<registry>.azurecr.io/<image>``
     - **Private** (Entra ID)
     - ``az acr login``
   * - **Amazon ECR** (private)
     - ``<acct>.dkr.ecr.<region>.amazonaws.com/<repo>``
     - **Private** (IAM)
     - ``aws ecr get-login-password``

.. warning::

   For client work where the image **must stay private**, choose a registry that is private
   by default — ghcr.io, Google Artifact Registry, Azure ACR, or Amazon ECR. **Docker Hub
   defaults to public:** a repo you push there is world-readable unless you *explicitly*
   create it as private. Whichever you pick, **verify the visibility in the registry UI after
   your first push** — do not assume.

An image name *is* its address: ``docker tag`` gives an existing image a second name pointing
at the registry, and ``docker push`` uploads it. The blocks below contact live registries and
require login — run them in your terminal, and replace every ``<PLACEHOLDER>``.

Docker Hub — public by default
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   docker login                                   # Docker Hub is the default registry
   docker tag amii-container-demo:0.1 <DOCKERHUB_USER>/amii-container-demo:0.1
   docker push <DOCKERHUB_USER>/amii-container-demo:0.1
   # ⚠️ New repos are PUBLIC. Make it private in Docker Hub → repo → Settings if needed.

GitHub Container Registry (ghcr.io) — private by default
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Matches an ``Amii-Engineering`` org repo and integrates cleanly with GitHub Actions.

.. code-block:: bash

   # Personal Access Token (classic) with: write:packages, read:packages
   echo "$GITHUB_TOKEN" | docker login ghcr.io -u <GITHUB_USER> --password-stdin
   docker tag amii-container-demo:0.1 ghcr.io/amii-engineering/amii-container-demo:0.1
   docker push ghcr.io/amii-engineering/amii-container-demo:0.1
   # Private by default; publish it explicitly in the package settings only if you want it public.

Google Artifact Registry (GCP) — private by default
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   # One-time: let Docker authenticate to Artifact Registry in your region.
   gcloud auth configure-docker <REGION>-docker.pkg.dev        # e.g. us-central1-docker.pkg.dev
   docker tag amii-container-demo:0.1 \
     <REGION>-docker.pkg.dev/<PROJECT_ID>/<REPO>/amii-container-demo:0.1
   docker push <REGION>-docker.pkg.dev/<PROJECT_ID>/<REPO>/amii-container-demo:0.1
   # Governed by IAM; nothing is public unless you grant allUsers the Artifact Registry Reader role.

Azure Container Registry / Amazon ECR — private by default
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   # Azure:
   az acr login --name <REGISTRY_NAME>
   docker tag amii-container-demo:0.1 <REGISTRY_NAME>.azurecr.io/amii-container-demo:0.1
   docker push <REGISTRY_NAME>.azurecr.io/amii-container-demo:0.1

   # Amazon ECR (note: "ECR Public" at public.ecr.aws is a SEPARATE, public-by-default service):
   aws ecr get-login-password --region <REGION> \
     | docker login --username AWS --password-stdin <ACCOUNT_ID>.dkr.ecr.<REGION>.amazonaws.com
   docker tag amii-container-demo:0.1 \
     <ACCOUNT_ID>.dkr.ecr.<REGION>.amazonaws.com/amii-container-demo:0.1
   docker push <ACCOUNT_ID>.dkr.ecr.<REGION>.amazonaws.com/amii-container-demo:0.1

.. tip::

   **Tagging discipline:** never rely on ``:latest`` for anything you need to reproduce. Tag
   with a version or the Git commit SHA (``:0.1``, ``:git-a1b2c3d``) so an image traces back
   to exact source — the same "pin the exact code behind a result" habit from the
   :doc:`Git guide </git_and_github/git_and_github>`.


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.

.. figure:: images/06_cicd_hpc.svg
   :width: 720px
   :align: center
   :alt: Commit to PR to CI tests to merge to image built and pushed to pulled and run on an HPC cluster.

   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``:

.. code-block:: yaml

   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 }}


.. _container-local-dev:

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.

.. figure:: images/05_local_dev.svg
   :width: 720px
   :align: center
   :alt: Host source directory bind-mounted into the container; edits appear live.

   With a bind mount, your editor writes to the host directory and the container sees the
   change instantly — no rebuild for source edits.

.. list-table::
   :widths: 45 55
   :header-rows: 1

   * - What you changed
     - What to do
   * - Source (``app.py``)
     - The volume syncs it instantly; ``--reload`` restarts the app. **No rebuild.**
   * - Dependencies or the ``Dockerfile``
     - The *image itself* is stale. **Rebuild it** with ``docker compose up --build``.

A development-specific Compose file (``docker-compose.dev.yml``) mounts the code, forces a
reload server, and is meant to be run with ``--build``:

.. code-block:: yaml

   # 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:

.. code-block:: bash

   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 :ref:`container-cmd` 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:

.. code-block:: dockerfile

   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:

.. code-block:: yaml

   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".

.. code-block:: bash

   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.

.. code-block:: make

   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 <https://github.com/casey/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``):

.. code-block:: text

   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.


.. _container-podman:

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:

.. code-block:: bash

   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.

.. code-block:: bash

   # 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
^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   ssh <USERNAME>@<HPC_HOSTNAME>          # confirm the real host with your HPC support team

Step 2 — Pull the image with Podman
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   # 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:

.. code-block:: bash

   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``:

.. code-block:: bash

   #!/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

.. code-block:: bash

   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:

.. code-block:: bash

   scp <USERNAME>@<HPC_HOSTNAME>:/project/<GROUP>/data/results.csv .


Best Practices
--------------

* **Pin everything** — base image tag (``python:3.11-slim``, not ``latest``) 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`` / ``alpine`` bases 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 ``USER`` line 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.


.. _container-exercises:

Hands-On Exercises
------------------

Work through these in order; together they exercise the full workflow.

.. admonition:: Lab 1 — Build and run
   :class: note

   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.

.. admonition:: Lab 2 — Caching and slimming
   :class: note

   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.

.. admonition:: Lab 3 — Compose and dev mode
   :class: note

   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.

.. admonition:: Lab 4 — Push and pull
   :class: note

   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
---------------

.. list-table::
   :widths: 46 54
   :header-rows: 1

   * - Command
     - Purpose
   * - ``docker build -t name:tag .``
     - Build an image from the ``Dockerfile`` in the current directory.
   * - ``docker images`` / ``docker history <img>``
     - List images / show an image's layers.
   * - ``docker run -d --rm -p 8000:8000 --name demo <img>``
     - Run a container: detached, auto-removed, port published, named.
   * - ``docker ps`` / ``docker ps -a``
     - List running / all (including stopped) containers.
   * - ``docker logs <name>`` / ``docker exec -it <name> /bin/bash``
     - View logs / open a shell inside a running container.
   * - ``docker stop <name>`` / ``docker rm <name>``
     - Stop a container / remove a stopped one.
   * - ``docker tag <img> <registry>/<repo>:tag`` / ``docker push ...``
     - Name an image for a registry / upload it.
   * - ``docker pull <registry>/<repo>:tag``
     - Download an image from a registry.
   * - ``docker compose up --build`` / ``docker compose down``
     - Start / stop a multi-container stack.
   * - ``docker system prune``
     - Reclaim space from stopped containers, dangling images, unused networks.
   * - ``apptainer pull demo.sif docker://<registry>/<repo>:tag``
     - Convert a registry image to a ``.sif`` for HPC.
   * - ``podman run --device nvidia.com/gpu=all <img>``
     - Run rootless with GPUs (on an HPC cluster).


Further Resources
-----------------

* `Docker documentation <https://docs.docker.com>`_ — the canonical reference for the CLI,
  Dockerfile, and Compose.
* `Dockerfile best practices <https://docs.docker.com/develop/develop-images/dockerfile_best-practices/>`_
  — layer ordering, small images, and caching in depth.
* `Podman <https://podman.io>`_ — the rootless, daemonless engine common on HPC clusters.
* `Apptainer <https://apptainer.org>`_ — the HPC container runtime (formerly Singularity).
* `GitHub Container Registry docs <https://docs.github.com/packages>`_ — ghcr.io, tokens, and
  package visibility.
* `Docker Compose <https://docs.docker.com/compose/>`_ — declaring and running multi-container
  applications.
