Lab 7 & 8 · Train, Containerize, Version and Deploy a Model API¶

CS203 Software Tools and Techniques for AI · IIT Gandhinagar · companion to Lecture 6

You'll take a tiny linear-regression model from your laptop to a versioned, containerized API, then swap it live from v1 to v2 and back by changing one line.

train → serve → containerize → debug → version → push → compose → deploy

The model is deliberately simple: this lab is about Docker, git and deployment, not accuracy.

Part What you do
0 · Setup Check Docker, git and Python
1 · Train Finish train.py and train model v1
2 · Serve Test the Flask API without Docker
3 · Containerize Write a Dockerfile and .dockerignore, build and run
4 · Debug Inspect the container, then break it on purpose
5 · Version git commits and tags, train v2, tag images
6 · Push Push images to a registry and code to a git remote
7 · Compose Describe the service in compose.yaml
8 · Deploy Swap v1 → v2 live, then roll back

How to work

  • Run this notebook locally (JupyterLab or VS Code), not on Colab: Colab has no Docker.
  • # TODO marks what you write. Each one has an Example showing the same pattern with different values: adapt it to the task, don't copy it.
  • Cells refuse to run while a TODO placeholder is left. In the Dockerfile, the TODO comments are the placeholders: delete each one once it's done.
  • # Check cells verify your work with ✅ / ❌.
  • Every cell is safe to re-run. Stuck? See Troubleshooting at the end.

Part 0 · Setup¶

You need Docker Desktop (or Docker Engine on Linux) running, Python 3.10+ with Jupyter, git, and about 3 GB of free disk. Put this notebook in an empty lab06 folder and start Jupyter from there.

  • Windows: run Jupyter inside WSL2.
  • macOS: port 5000 is taken by AirPlay, so the local registry uses 5001.

Run the three cells below: install packages, load the helper functions (collapsed, no need to read them), and check Docker.

In [ ]:
%pip install -q scikit-learn numpy scipy joblib flask gunicorn requests
In [ ]:
# Helper functions used throughout the lab (sh, ok, wait_for, ...). No need to change them.
import json, os, platform, re, shutil, subprocess, sys, tempfile, threading, time
from pathlib import Path

import numpy as np
import requests

LAB = Path.cwd()          # the lab06 folder; every path in this notebook is relative to it
IMAGE = "reg-api"         # local image name
LABEL = "lab06=1"         # every container we start carries this label, so cleanup() can find it
REG = "localhost:5001"    # local registry (Part 6)


def sh(cmd, check=False, quiet=False, env=None):
    """Run a shell command, stream its output, return (exit_code, output, seconds)."""
    if "TODO" in cmd:
        raise ValueError("This command still contains TODO. Fill it in first.")
    if not quiet:
        print(f"$ {cmd}")
    start = time.perf_counter()
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            text=True, encoding="utf-8", errors="replace",
                            env={**os.environ, **(env or {})})
    lines = []
    for line in proc.stdout:
        lines.append(line)
        if not quiet:
            print(line, end="")
    proc.wait()
    secs = time.perf_counter() - start
    if check and proc.returncode != 0:
        raise RuntimeError(f"exit code {proc.returncode}: {cmd}")
    return proc.returncode, "".join(lines), secs


def fresh(name):
    """Force-remove a container if it exists, so the cell that starts it can be re-run."""
    subprocess.run(f"docker rm -f {name}", shell=True, capture_output=True)


def cleanup():
    """Remove every container this lab started (they all carry the lab06 label)."""
    ids = subprocess.run(f"docker ps -aq --filter label={LABEL}", shell=True,
                         capture_output=True, text=True).stdout.split()
    if ids:
        subprocess.run("docker rm -f " + " ".join(ids), shell=True, capture_output=True)
    print(f"Removed {len(ids)} lab container(s).")


def status(name):
    """Print a container's state: running, exited (with exit code), ..."""
    sh('docker inspect --format "{{.Name}} -> {{.State.Status}} (exit code {{.State.ExitCode}})" ' + name)


def wait_for(url, timeout=30):
    """Poll url until it returns HTTP 200; return the response or raise TimeoutError."""
    deadline, last = time.time() + timeout, None
    while time.time() < deadline:
        try:
            r = requests.get(url, timeout=3)
            if r.status_code == 200:
                return r
            last = f"HTTP {r.status_code}"
        except requests.RequestException as e:
            last = type(e).__name__
        time.sleep(0.5)
    raise TimeoutError(f"{url} not ready after {timeout}s (last: {last}). Check `docker logs`.")


def inspect_image(ref):
    """Return `docker image inspect` metadata for an image, or None if it doesn't exist locally."""
    r = subprocess.run(f"docker image inspect {ref}", shell=True, capture_output=True,
                       text=True, encoding="utf-8", errors="replace")
    return json.loads(r.stdout)[0] if r.returncode == 0 else None


def ok(cond, msg):
    """Print a ✅ / ❌ line for self-checks."""
    print(("✅ " if cond else "❌ ") + msg)
    return bool(cond)


def git_sha(ref="HEAD"):
    """Short commit SHA of a ref (branch, tag, HEAD)."""
    r = subprocess.run(f"git rev-list -n 1 --abbrev-commit {ref}", shell=True, capture_output=True, text=True)
    return r.stdout.strip() or "nogit"


def set_env(key, value, path=".env"):
    """Set one KEY=value line in a .env file (adds it if missing)."""
    if "TODO" in str(value):
        raise ValueError("Fill in the value first (it still contains TODO).")
    p = Path(path)
    lines = p.read_text().splitlines() if p.exists() else []
    lines = [l for l in lines if not l.startswith(key + "=")] + [f"{key}={value}"]
    p.write_text("\n".join(lines) + "\n")


def predict(url, payload):
    """POST a request body to url/predict and return the JSON reply."""
    r = requests.post(f"{url}/predict", json=payload, timeout=10)
    r.raise_for_status()
    return r.json()


def start_poller(url, seconds=12, interval=0.1):
    """Hit url repeatedly in a background thread; returns (thread, stats dict)."""
    stats = {"ok": 0, "failed": 0, "versions_seen": {}}

    def run():
        end = time.time() + seconds
        while time.time() < end:
            try:
                v = requests.get(url, timeout=1).json()["app_version"]
                stats["ok"] += 1
                stats["versions_seen"][v] = stats["versions_seen"].get(v, 0) + 1
            except Exception:
                stats["failed"] += 1
            time.sleep(interval)

    t = threading.Thread(target=run, daemon=True)
    t.start()
    return t, stats


print("Python", platform.python_version(), "|", platform.system(), platform.machine())
print("Lab folder:", LAB)

What the check cell runs:

Command What it does
docker version print the versions of the Docker client (the CLI) and server (the daemon); fails if the daemon isn't running
↳ --format "..." print only chosen fields, picked with a Go template such as {{.Server.Version}}
docker run hello-world download the tiny hello-world test image and run it once
↳ --rm delete the container as soon as it exits
git --version check that git is installed
In [ ]:
# If this fails with "Cannot connect to the Docker daemon", start Docker Desktop and re-run.
sh('docker version --format "Docker client {{.Client.Version}}, server {{.Server.Version}} ({{.Server.Os}}/{{.Server.Arch}})"', check=True)
sh("docker run --rm hello-world", check=True)
sh("git --version", check=True)

Part 1 · Train the model¶

train.py fits a linear regression on scikit-learn's Diabetes dataset (442 patients, 10 features) and saves two files:

  • model.joblib: the fitted model
  • metadata.json: version, metrics, feature order, and the exact library versions used for training

Its settings come from environment variables (listed in the docstring), so the same script can later produce v2. Complete TODOs 1.1 to 1.4.

In [ ]:
%%writefile train.py
"""Train a linear-regression model and write deployable artifacts.

Configured through environment variables, so the same script produces every model version:
  MODEL_VERSION  version recorded in the metadata          (default 1.0.0)
  TRAIN_FRAC     fraction of the training set to use       (default 0.2)
  SEED           split seed                                (default 42)
  OUTPUT_DIR     where the artifacts are written           (default models/v1)
"""
import json
import os
import platform
from datetime import datetime, timezone
from pathlib import Path

import joblib
import numpy as np
import sklearn
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split


def load_split(seed=42):
    """Return (X_train, X_test, y_train, y_test, feature_names)."""
    data = load_diabetes()
    # TODO 1.1: split data.data / data.target into 75% train and 25% test with train_test_split
    #           (test_size=0.25, random_state=seed)
    # Example:  a_tr, a_te, b_tr, b_te = train_test_split(features, labels, test_size=0.3, random_state=7)
    X_tr, X_te, y_tr, y_te = TODO
    return X_tr, X_te, y_tr, y_te, list(data.feature_names)


def main():
    # TODO 1.2: read the four settings from environment variables, using the defaults from the docstring
    #           (os.environ.get); frac must be a float, seed an int, out a Path
    # Example:  name   = os.environ.get("USER_NAME", "guest")        # returns a string
    #           ratio  = float(os.environ.get("RATIO", "0.5"))      # convert when you need a number
    #           count  = int(os.environ.get("COUNT", "3"))
    #           folder = Path(os.environ.get("DATA_DIR", "data/raw"))
    version = TODO
    frac = TODO
    seed = TODO
    out = TODO

    X_tr, X_te, y_tr, y_te, features = load_split(seed)
    n = max(20, int(len(X_tr) * frac))
    # TODO 1.3: fit a LinearRegression on the FIRST n training rows only (X_tr[:n], y_tr[:n])
    # Example:  m = Ridge().fit(a_tr[:k], b_tr[:k])       # .fit() returns the fitted model
    model = TODO
    # TODO 1.4: predict on the test set, then compute r2 (r2_score) and rmse (square root of mean_squared_error)
    # Example:  b_hat = m.predict(a_te)
    #           score = r2_score(b_te, b_hat)                     # (true values, predictions)
    #           err   = np.sqrt(mean_squared_error(b_te, b_hat))
    pred = TODO
    r2 = TODO
    rmse = TODO

    out.mkdir(parents=True, exist_ok=True)
    joblib.dump(model, out / "model.joblib")
    metadata = {
        "model_version": version,
        "model_type": "LinearRegression",
        "train_frac": frac,
        "n_train": n,
        "seed": seed,
        "test_r2": round(float(r2), 4),
        "test_rmse": round(float(rmse), 3),
        "feature_names": features,
        "dataset": "sklearn.datasets.load_diabetes",
        "trained_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "trained_on": f"{platform.system()} {platform.machine()}",
        "python_version": platform.python_version(),
        "sklearn_version": sklearn.__version__,
        "numpy_version": np.__version__,
    }
    (out / "metadata.json").write_text(json.dumps(metadata, indent=2))
    print(f"[train] LinearRegression v{version}: n_train={n}, test R2={r2:.3f}, RMSE={rmse:.1f} -> {out}/")


if __name__ == "__main__":
    main()
In [ ]:
# Train v1 with the default settings
code = [line.split("#")[0] for line in Path("train.py").read_text().splitlines()]
assert not any("TODO" in line for line in code), "train.py still has a TODO placeholder: finish 1.1 to 1.4 and re-run the cell above"
sh(f'"{sys.executable}" train.py', check=True)
print(Path("models/v1/metadata.json").read_text())
In [ ]:
# Check
import importlib, joblib
import train as train_mod
from sklearn.metrics import r2_score

importlib.reload(train_mod)
X_tr, X_te, y_tr, y_te, feats = train_mod.load_split(42)
m1 = joblib.load("models/v1/model.joblib")
meta1 = json.loads(Path("models/v1/metadata.json").read_text())

ok(type(m1).__name__ == "LinearRegression" and len(m1.coef_) == 10, "model.joblib is a LinearRegression with 10 coefficients")
ok(len(X_tr) == 331 and len(X_te) == 111, f"75/25 split: {len(X_tr)} train rows, {len(X_te)} test rows")
ok(meta1["n_train"] == max(20, int(len(X_tr) * 0.2)), f"v1 used the first 20% of the training rows (n_train={meta1['n_train']})")
ok(abs(r2_score(y_te, m1.predict(X_te)) - meta1["test_r2"]) < 1e-3, f"metadata test_r2 {meta1['test_r2']} matches the saved model")
In [ ]:
# Pin each dependency to the exact version installed here, so the container
# unpickles the model with the same libraries that pickled it.
from importlib.metadata import version as pkg_version

PKGS = ["scikit-learn", "numpy", "scipy", "joblib", "flask", "gunicorn"]
Path("requirements.txt").write_text("".join(f"{p}=={pkg_version(p)}\n" for p in PKGS))
print(Path("requirements.txt").read_text())

PY_MM = ".".join(platform.python_version_tuple()[:2])
print(f"Your Python is {PY_MM}: use python:{PY_MM}-slim as the base image in Part 3")

Think about it: Open models/v1/metadata.json. Which fields would you check first if the model loads on your laptop but fails on a server? Which one protects against feeding features in the wrong order?


Part 2 · Serve the model as an API¶

app.py is a small Flask service. It's given; you don't need to change it.

Endpoint Returns
GET /health {"status": "ok"}, used by health checks
GET /version app version, git SHA, model metadata, hostname
POST /predict predictions for {"instances": [{feature: value, ...}, ...]}

We test it first with Flask's test client: no server and no Docker yet.

In [ ]:
%%writefile app.py
"""Linear-regression HTTP API.

Configuration (environment variables):
  MODEL_DIR    folder holding model.joblib + metadata.json   (default: model)
  APP_VERSION  version string of this deployment             (default: dev)
  GIT_SHA      commit this image was built from              (default: unknown)
"""
import json
import logging
import os
import platform
import socket
from pathlib import Path

import joblib
import numpy as np
import sklearn
from flask import Flask, jsonify, request

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("reg-api")

MODEL_DIR = Path(os.environ.get("MODEL_DIR", "model"))
APP_VERSION = os.environ.get("APP_VERSION", "dev")
GIT_SHA = os.environ.get("GIT_SHA", "unknown")

# Load once at startup. If the model is missing, fail fast and loudly: a server that starts
# without its model is worse than one that refuses to start.
model = joblib.load(MODEL_DIR / "model.joblib")
metadata = json.loads((MODEL_DIR / "metadata.json").read_text())
FEATURES = metadata["feature_names"]
if metadata["sklearn_version"] != sklearn.__version__:
    log.warning("Model was trained with scikit-learn %s but this runtime has %s",
                metadata["sklearn_version"], sklearn.__version__)

app = Flask(__name__)
log.info("Loaded model v%s from %s (app %s, commit %s)",
         metadata["model_version"], MODEL_DIR, APP_VERSION, GIT_SHA)


@app.get("/")
def index():
    return jsonify(service="reg-api", app_version=APP_VERSION, endpoints=["/health", "/version", "/predict (POST)"])


@app.get("/health")
def health():
    return jsonify(status="ok")


@app.get("/version")
def version():
    return jsonify(
        app_version=APP_VERSION,
        git_sha=GIT_SHA,
        model=metadata,
        runtime={"python": platform.python_version(), "sklearn": sklearn.__version__,
                 "numpy": np.__version__, "platform": f"{platform.system()} {platform.machine()}"},
        hostname=socket.gethostname(),
    )


@app.post("/predict")
def predict():
    body = request.get_json(silent=True) or {}
    instances = body.get("instances")
    if not isinstance(instances, list) or not instances:
        return jsonify(error='Expected JSON body {"instances": [{feature: value, ...}, ...]}'), 400
    rows = []
    for i, inst in enumerate(instances):
        missing = [f for f in FEATURES if f not in inst] if isinstance(inst, dict) else FEATURES
        if missing:
            return jsonify(error=f"instance {i} is missing features: {missing}"), 400
        try:
            rows.append([float(inst[f]) for f in FEATURES])   # enforce the training feature order
        except (TypeError, ValueError):
            return jsonify(error=f"instance {i} has a non-numeric value"), 400
    preds = [round(float(p), 4) for p in model.predict(np.asarray(rows))]
    return jsonify(predictions=preds, model_version=metadata["model_version"], app_version=APP_VERSION)
In [ ]:
os.environ["MODEL_DIR"] = "models/v1"
import importlib
import app as reg_app
importlib.reload(reg_app)                       # picks up edits if you re-run this cell
client = reg_app.app.test_client()

from train import load_split
X_tr, X_te, y_tr, y_te, FEATURES = load_split(seed=42)


def to_instances(X):
    """Turn a 2-D array into the API's request body."""
    return {"instances": [dict(zip(FEATURES, map(float, row))) for row in X]}


sample = to_instances(X_te[:3])
Path("sample_request.json").write_text(json.dumps(sample, indent=2))   # reused in later parts

print(client.get("/health").json)
resp = client.post("/predict", json=sample)
print(resp.status_code, json.dumps(resp.json, indent=2))
print("true values:", y_te[:3].tolist())
In [ ]:
# TODO 2.1: send the WHOLE test set X_te to /predict in ONE request (use `client` and `to_instances`),
#           then store the R² against y_te in `api_r2`. It should equal test_r2 from training.
# Example (first 5 rows only):
#   resp  = client.post("/predict", json=to_instances(X_te[:5]))
#   preds = resp.json["predictions"]
#   score = r2_score(y_te[:5], preds)
api_r2 = None

# Check
meta_v1 = json.loads(Path("models/v1/metadata.json").read_text())
ok(api_r2 is not None and abs(api_r2 - meta_v1["test_r2"]) < 1e-3,
   f"API R² {api_r2} matches training R² {meta_v1['test_r2']}")

Think about it: app.py refuses to start if the model file is missing, instead of starting and failing on every request. Why is failing fast better for a container on a cloud platform?


Part 3 · Containerize¶

Fill in the Dockerfile skeleton below; each TODO describes one step. These are the instructions you'll need:

Instruction What it does
FROM <image>:<tag> the base image everything else is built on top of
WORKDIR <path> set the working directory for the following instructions and for the running container (created if missing)
COPY <src> <dest> copy files from the build context into the image; a relative <dest> is relative to WORKDIR
RUN <command> run a shell command at build time; its result is saved as a new layer
ARG <NAME>=<default> a build-time variable, set with docker build --build-arg NAME=value; not available once the container runs
ENV <NAME>=<value> an environment variable baked into the image and visible to the running app; ENV NAME=${NAME} copies an ARG into it
LABEL <key>=<value> metadata stored on the image, readable with docker image inspect
EXPOSE <port> documents which port the app listens on; it does not publish it (that's docker run -p)
USER <name> run the following instructions, and the container itself, as this user instead of root
HEALTHCHECK CMD <command> a command Docker runs periodically inside the container: exit code 0 means healthy
CMD <command> the default command when the container starts. Shell form (CMD exec gunicorn ...) runs through sh, so $PORT is expanded; exec then replaces the shell with gunicorn, so gunicorn receives Docker's stop signal

Non-Docker pieces for TODOs 6 and 8: useradd -u 1000 <name> creates a user with uid 1000; gunicorn takes --bind <host>:<port>, --workers <n> and --access-logfile - (log each request to stdout, where docker logs shows it).

Example: the same eight steps for a different app (server.py, Python 3.11, port 9000). Yours uses the names and values from the TODOs.

# 1. base image
FROM python:3.11-slim

# 2. working directory
WORKDIR /srv

# 3. dependencies first
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 4. application code
COPY server.py .

# 5. build args -> env vars, labels, port
ARG RELEASE=dev
ARG COMMIT=unknown
ENV RELEASE=${RELEASE} COMMIT=${COMMIT} PORT=9000
LABEL org.opencontainers.image.version=${RELEASE} \
      org.opencontainers.image.revision=${COMMIT}
EXPOSE 9000

# 6. non-root user
RUN useradd -u 1001 appuser
USER appuser

# 7. health check (exit code 0 = healthy)
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:9000/ping')"

# 8. start command
CMD exec gunicorn --bind 0.0.0.0:$PORT --workers 4 --access-logfile - server:app
In [ ]:
%%writefile Dockerfile
# Replace each TODO comment with the instruction(s) it describes (see the example above), then delete the comment.

# TODO 1: base image python:<major.minor>-slim, matching the Python version printed in Part 1
FROM TODO

# TODO 2: working directory /app

# TODO 3: copy ONLY requirements.txt, then: pip install --no-cache-dir -r requirements.txt

# TODO 4: copy app.py (keep the two model lines below as they are)
ARG MODEL_SRC=models/v1
COPY ${MODEL_SRC}/ ./model/

# TODO 5: ARG APP_VERSION (default dev) and ARG GIT_SHA (default unknown)
#         ENV APP_VERSION, GIT_SHA and PORT=8080
#         LABEL org.opencontainers.image.version and org.opencontainers.image.revision
#         EXPOSE 8080

# TODO 6: create a non-root user with uid 1000 (RUN useradd ...), then switch to it with USER

# TODO 7: HEALTHCHECK that requests /health with Python's urllib (slim images have no curl)

# TODO 8: shell-form CMD: exec gunicorn on 0.0.0.0:$PORT, 2 workers, --access-logfile -, app:app

.dockerignore lists what must not be sent to Docker when building. Anything in the build context can end up in an image layer, and images get pushed to registries.

Keep out: notebooks and checkpoints, __pycache__, virtual environments, .git, and all .env files.

Example for a different project. One pattern per line, like .gitignore: * matches any characters, **/ matches at any folder depth, and a folder name excludes the whole folder.

*.log
**/node_modules
build/
.DS_Store
secrets*
In [ ]:
%%writefile .dockerignore
# TODO: one pattern per line (see the example above)

Build the image¶

docker build -t reg-api:dev .
Command What it does
docker build build an image by running the Dockerfile instructions in order
↳ -t reg-api:dev name the result: image reg-api, tag dev
↳ . the build context: this folder (minus .dockerignore entries) is sent to Docker, and COPY can only see files inside it

The cell also prints how big the build context was: a small number means .dockerignore is doing its job.

In [ ]:
assert "TODO" not in Path("Dockerfile").read_text(), "Your Dockerfile still contains TODO"
rc, out, secs = sh(f"docker build -t {IMAGE}:dev .")
ctx = re.findall(r"transferring context: ([\d.]+\s*[kMG]?B)", out)
print(f"\nBuild finished in {secs:.1f}s (exit code {rc}); build context sent: {ctx[-1] if ctx else 'n/a'}")
Command What it does
docker history reg-api:dev list the image's layers, newest first
↳ --format "table {{.Size}}\t{{.CreatedBy}}" show only each layer's size and the instruction that created it, as a table
docker images reg-api list local images named reg-api, with tag, image ID and size
In [ ]:
# Which instruction created which layer, and how big is each one?
sh("docker history " + IMAGE + ':dev --format "table {{.Size}}\\t{{.CreatedBy}}"')
sh("docker images " + IMAGE)
Command What it does
docker image inspect reg-api:dev print the image's configuration as JSON (user, ports, env, labels, healthcheck); used by inspect_image()
docker run --rm reg-api:dev <command> start a throwaway container that runs <command> instead of the image's CMD, then deletes itself; used to look inside the image
In [ ]:
# Check: inspects the image metadata and looks inside the image
def check_part3(ref=f"{IMAGE}:dev"):
    img = inspect_image(ref)
    if not ok(img is not None, f"image {ref} exists"):
        return
    cfg = img["Config"]
    env = dict(e.split("=", 1) for e in cfg.get("Env") or [])
    labels = cfg.get("Labels") or {}
    ok(img["Size"] / 1e6 < 800, f"image size {img['Size'] / 1e6:.0f} MB (< 800 MB)")
    ok(cfg.get("User") not in (None, "", "root", "0"), f"runs as a non-root user (User={cfg.get('User')!r})")
    ok("8080/tcp" in (cfg.get("ExposedPorts") or {}), "exposes 8080/tcp")
    ok(env.get("PORT") == "8080", "PORT=8080 is set")
    ok("APP_VERSION" in env and "GIT_SHA" in env, f"APP_VERSION / GIT_SHA are set ({env.get('APP_VERSION')!r}, {env.get('GIT_SHA')!r})")
    ok("org.opencontainers.image.version" in labels and "org.opencontainers.image.revision" in labels, "OCI version + revision labels present")
    ok(cfg.get("Healthcheck") is not None, "HEALTHCHECK defined")

    meta = json.loads(Path("models/v1/metadata.json").read_text())
    code_, out, _ = sh(f'docker run --rm {ref} python -c "import platform, sklearn; '
                       f'print(platform.python_version(), sklearn.__version__)"', quiet=True)
    py_in, skl_in = out.split()[-2:] if code_ == 0 else ("?", "?")
    ok(py_in.rsplit(".", 1)[0] == meta["python_version"].rsplit(".", 1)[0],
       f"container Python {py_in} matches training Python {meta['python_version']} (major.minor)")
    ok(skl_in == meta["sklearn_version"], f"container scikit-learn {skl_in} == training {meta['sklearn_version']}")
    _, out, _ = sh(f"docker run --rm {ref} ls model", quiet=True)
    ok("model.joblib" in out and "metadata.json" in out, "model artifacts are baked in at /app/model")

    ignore = Path(".dockerignore").read_text() if Path(".dockerignore").exists() else ""
    patterns = [l.strip() for l in ignore.splitlines() if l.strip() and not l.startswith("#")]
    ok(all(any(key in p for p in patterns) for key in ["ipynb", ".git", "__pycache__", ".env"]),
       f".dockerignore covers notebooks, .git, __pycache__, .env ({len(patterns)} patterns)")


check_part3()

Run it¶

docker rm -f lab06-api
docker run -d --name lab06-api --label lab06=1 -p 8000:8080 reg-api:dev
Command What it does
docker rm -f lab06-api run by fresh("lab06-api"): remove any old container with that name so the cell can be re-run
↳ -f force: stop the container first if it's still running
docker run ... reg-api:dev create a container from the image reg-api:dev and start it
↳ -d detached: run in the background and give the prompt back
↳ --name lab06-api a fixed name, so later commands can refer to this container
↳ --label lab06=1 a key=value tag on the container, so cleanup() can find every lab container
↳ -p 8000:8080 publish a port: localhost:8000 on your machine forwards to port 8080 inside the container
In [ ]:
sample = json.loads(Path("sample_request.json").read_text())

fresh("lab06-api")
sh(f"docker run -d --name lab06-api --label {LABEL} -p 8000:8080 {IMAGE}:dev", check=True)
print(wait_for("http://localhost:8000/health").json())
print(predict("http://localhost:8000", sample))
v = requests.get("http://localhost:8000/version").json()
print("container hostname:", v["hostname"], "| your laptop:", platform.node(), "| runtime:", v["runtime"]["platform"])

Think about it

  • Why does the Dockerfile install requirements.txt before copying app.py and the model? Which of these changes most often?
  • Which two .dockerignore entries prevent a security problem, and what could leak without them?

Part 4 · Debug¶

Look at the running container from the outside, then trigger three classic failures so you recognise them later.

4.1 Inspect¶

Command What it does
docker ps list running containers (add -a to include stopped ones)
↳ --filter name=lab06-api only containers whose name matches
docker logs lab06-api print everything the container wrote to stdout/stderr (here: gunicorn's startup and access log)
↳ --tail 10 only the last 10 lines
docker stats lab06-api CPU, memory and network usage of the container
↳ --no-stream print one snapshot and exit, instead of updating live
docker exec lab06-api whoami run a command inside the running container; whoami shows which user the app runs as
docker exec lab06-api ls -la /app/model list the model files baked into the image
docker exec -it lab06-api bash (optional, in a terminal) open a shell inside the container; type exit to leave
↳ -it -i keeps input open, -t gives you a terminal: both are needed for an interactive shell
In [ ]:
sh("docker ps --filter name=lab06-api")
sh("docker logs --tail 10 lab06-api")          # note the gunicorn access-log lines for your requests
sh("docker stats --no-stream lab06-api")
sh("docker exec lab06-api whoami")
sh("docker exec lab06-api ls -la /app/model")
# optional, in a terminal:  docker exec -it lab06-api bash

4.2 Wrong bind address¶

docker run -d --name lab06-bad-bind --label lab06=1 -p 8001:8080 reg-api:dev gunicorn --bind 127.0.0.1:8080 app:app
Command What it does
docker run ... reg-api:dev same as in Part 3, on host port 8001
↳ gunicorn --bind 127.0.0.1:8080 app:app anything after the image name replaces the image's CMD: here gunicorn listens on 127.0.0.1 instead of 0.0.0.0
docker exec lab06-bad-bind python -c "..." send the same /health request from inside the container
In [ ]:
fresh("lab06-bad-bind")
sh(f"docker run -d --name lab06-bad-bind --label {LABEL} -p 8001:8080 {IMAGE}:dev "
   "gunicorn --bind 127.0.0.1:8080 app:app", check=True)
time.sleep(4)
try:
    print("From the host:", requests.get("http://localhost:8001/health", timeout=3).json())
except requests.RequestException as e:
    print("From the host: FAILED with", type(e).__name__)
sh('docker exec lab06-bad-bind python -c "import urllib.request; '
   "print('From inside:', urllib.request.urlopen('http://127.0.0.1:8080/health').read())\"")

4.3 A container that won't stay up¶

docker run -d --name lab06-no-model --label lab06=1 -e MODEL_DIR=/nowhere reg-api:dev
Command What it does
docker run ... reg-api:dev start the API as before (no -p: we won't send it requests)
↳ -e MODEL_DIR=/nowhere set an environment variable inside the container; here it points the app at a folder that doesn't exist
docker inspect lab06-no-model run by status(): shows whether the container is running or exited, and its exit code
↳ --format "{{.State.Status}} ..." print only those fields

For the TODO: docker logs <container> also works on containers that have already exited.

In [ ]:
fresh("lab06-no-model")
sh(f"docker run -d --name lab06-no-model --label {LABEL} -e MODEL_DIR=/nowhere {IMAGE}:dev", check=True)
time.sleep(5)
status("lab06-no-model")
# TODO 4.3: print this container's logs and find the ROOT cause (the first real error, not the last line).
# Example (a different container):  sh("docker logs --tail 20 lab06-api")

4.4 Port already taken¶

Command What it does
docker run ... -p 8000:8080 reg-api:dev try to start a second container on host port 8000, which lab06-api is already using
In [ ]:
rc, out, _ = sh(f"docker run -d --name lab06-clash --label {LABEL} -p 8000:8080 {IMAGE}:dev", quiet=True)
print(f"exit code {rc}:", out.strip()[-250:])

Think about it

  • 4.2: Why did the request from inside the container work while the one from the host failed? Which address must a server bind to inside a container?
  • 4.3: What was the root cause? Would --restart=always have helped?

cleanup() removes every container this lab started:

Command What it does
docker ps --filter label=lab06=1 find containers carrying the lab's label
↳ -a include stopped containers
↳ -q print only container IDs
docker rm -f <ids> remove them; -f stops running ones first
In [ ]:
cleanup()   # remove the debugging containers before moving on

Part 5 · Version¶

Code, Dockerfile, models and CHANGELOG.md go into git, tagged v1.0.0 and v2.0.0. Run-time settings go in .env, which is never committed (commit .env.example instead).

Images get tags too:

Tag Example Use for
release reg-api:2.0.0 deployments and rollbacks (never moves)
commit reg-api:sha-3f2c1ab tracing an image back to its code (never moves)
latest reg-api:latest local convenience only (moves all the time)

5.1 .gitignore, .env and the repository¶

In [ ]:
# TODO 5.1: write .gitignore. Keep out: Python bytecode caches, Jupyter checkpoints, virtual environments, and .env
# Example (a different project):
#   gitignore = """*.log
#   build/
#   node_modules/
#   """
gitignore = """TODO"""      # one pattern per line
assert "TODO" not in gitignore, "fill in gitignore first"
Path(".gitignore").write_text(gitignore)
In [ ]:
# .env holds run-time settings for Compose (Part 7). Not committed; .env.example is.
env_text = "API_TAG=1.0.0\nHOST_PORT=8000\n"
Path(".env").write_text(env_text)
Path(".env.example").write_text(env_text)
Path("CHANGELOG.md").write_text("# Changelog\n\n## 1.0.0\n- Baseline model: LinearRegression on 20% of the training data (models/v1)\n")

sh("git init -q")
sh("git symbolic-ref HEAD refs/heads/main")                     # call the branch `main`
if not sh("git config user.email", quiet=True)[1].strip():      # no git identity yet: set one for this repo only
    sh('git config user.email "student@example.com" && git config user.name "Lab Student"')

sh("git status --short")          # is .env listed? (it must not be)
sh("git check-ignore -v .env")    # which rule is hiding it?

5.2 Release 1.0.0: commit and tag¶

Command What it does
git add -A stage every new, changed and deleted file (files matched by .gitignore are skipped)
git commit -m "<message>" save the staged files as a new commit
git tag -a <tag> -m "<message>" put an annotated tag (with author, date and message) on the current commit
In [ ]:
# TODO 5.2: commit everything as "release 1.0.0" and mark that commit with an ANNOTATED tag v1.0.0
# Each list item is one shell command; they run in order. Example (a different release):
#   git_cmds = ["git add -A",
#               'git commit -m "release 0.9.0"',
#               'git tag -a v0.9.0 -m "release 0.9.0"']
git_cmds_v1 = ["TODO"]
for c in git_cmds_v1:
    sh(c, check=True)
SHA1 = git_sha("v1.0.0")
print("v1.0.0 is commit", SHA1)
sh("git log --oneline --decorate")

5.3 Release 2.0.0¶

Same train.py; only the environment variables change.

In [ ]:
# TODO 5.3a: v2 uses ALL the training data. Fill in the env vars: MODEL_VERSION=2.0.0, TRAIN_FRAC=1.0, OUTPUT_DIR=models/v2
# Example:  {"MODEL_VERSION": "0.5.0", "TRAIN_FRAC": "0.5", "OUTPUT_DIR": "models/v0"}   (values must be strings)
v2_env = None
assert v2_env, "fill in v2_env first"
sh(f'"{sys.executable}" train.py', env=v2_env, check=True)
In [ ]:
meta_v1 = json.loads(Path("models/v1/metadata.json").read_text())
meta_v2 = json.loads(Path("models/v2/metadata.json").read_text())
for m in (meta_v1, meta_v2):
    print(f"v{m['model_version']}: n_train={m['n_train']:<4} test R²={m['test_r2']}  RMSE={m['test_rmse']}")

with open("CHANGELOG.md", "a") as f:
    f.write("\n## 2.0.0\n- Retrained on 100% of the training data (models/v2); higher R², lower RMSE\n")

# TODO 5.3b: commit as "release 2.0.0" and create the annotated tag v2.0.0 (same pattern as the 5.2 example)
git_cmds_v2 = ["TODO"]
for c in git_cmds_v2:
    sh(c, check=True)
SHA2 = git_sha("v2.0.0")
print("v2.0.0 is commit", SHA2)
sh("git log --oneline --decorate")
sh("git diff --stat v1.0.0 v2.0.0")       # what changed between the two releases?

5.4 One image per release¶

Same Dockerfile; only the --build-args differ.

docker build --build-arg APP_VERSION=1.0.0 --build-arg GIT_SHA=<SHA1> --build-arg MODEL_SRC=models/v1 -t reg-api:1.0.0 .
docker tag reg-api:1.0.0 reg-api:sha-<SHA1>
Command What it does
docker build ... -t reg-api:1.0.0 . build as in Part 3, tagged with the release version
↳ --build-arg APP_VERSION=1.0.0 sets the Dockerfile's ARG APP_VERSION for this build only
↳ --build-arg GIT_SHA=<SHA1> records the git commit; it ends up in the image label and on /version
↳ --build-arg MODEL_SRC=models/v1 chooses which model folder is copied into the image
docker tag reg-api:1.0.0 reg-api:sha-<SHA1> add a second name to the same image: nothing is copied or rebuilt
docker images reg-api list all tags; tags of the same image share an IMAGE ID

The v2 build reuses the cached pip install layer, so it's much faster than the first build.

In [ ]:
V1, V2 = "1.0.0", "2.0.0"
sh(f"docker build --build-arg APP_VERSION={V1} --build-arg GIT_SHA={SHA1} --build-arg MODEL_SRC=models/v1 -t {IMAGE}:{V1} .", check=True)
sh(f"docker tag {IMAGE}:{V1} {IMAGE}:sha-{SHA1}")

# TODO 5.4: build reg-api:2.0.0 from models/v2 (same build-arg pattern, with SHA2),
#           then `docker tag` it as sha-<SHA2> and as latest
# Example: the two v1 commands above, written as list items (f-strings work inside the list):
#   cmds = [f"docker build --build-arg APP_VERSION={V1} --build-arg GIT_SHA={SHA1} --build-arg MODEL_SRC=models/v1 -t {IMAGE}:{V1} .",
#           f"docker tag {IMAGE}:{V1} {IMAGE}:sha-{SHA1}"]
cmds_v2 = ["TODO"]
for c in cmds_v2:
    sh(c, check=True)
sh(f"docker images {IMAGE}")
In [ ]:
# Check: tags, labels, and what is really baked inside each release
ids = {t: (inspect_image(f"{IMAGE}:{t}") or {}).get("Id") for t in [V1, V2, "latest", f"sha-{SHA1}", f"sha-{SHA2}"]}
ok(ids[V1] is not None and ids[V1] != ids[V2], "1.0.0 and 2.0.0 are different images")
ok(ids["latest"] is not None and ids["latest"] == ids[V2], "latest points at 2.0.0")
ok(ids[f"sha-{SHA1}"] == ids[V1] and ids[f"sha-{SHA2}"] == ids[V2], "commit tags point at their releases")
ok(sh("git tag", quiet=True)[1].split() == ["v1.0.0", "v2.0.0"], "git tags v1.0.0 and v2.0.0 exist")
ok(sh("git check-ignore .env", quiet=True)[0] == 0 and ".env" not in sh("git ls-files", quiet=True)[1].split(), ".env is ignored and not tracked")

for v, sha in [(V1, SHA1), (V2, SHA2)]:
    labels = (inspect_image(f"{IMAGE}:{v}") or {}).get("Config", {}).get("Labels") or {}
    ok(labels.get("org.opencontainers.image.version") == v, f"{v}: version label = {labels.get('org.opencontainers.image.version')}")
    ok(labels.get("org.opencontainers.image.revision") == sha, f"{v}: revision label = {labels.get('org.opencontainers.image.revision')} (git {sha})")
    inside = sh(f'docker run --rm {IMAGE}:{v} python -c "import json; '
                f"print(json.load(open('model/metadata.json'))['model_version'])\"", quiet=True)[1].strip()
    ok(inside.endswith(v), f"{v}: the model baked inside reports model_version {inside!r}")

Think about it

  • How is docker tag reg-api:2.0.0 reg-api:latest different from git tag v2.0.0?
  • A production container reports git_sha: 3f2c1ab on /version. How do you find the exact code and model it runs?
  • Why is .env.example committed but .env is not?

Part 6 · Push¶

Two things leave your laptop: the image goes to a container registry, the code goes to a git remote. Here both are local stand-ins (a registry:2 container on port 5001 and a bare git repo in a temp folder). With Docker Hub or GitHub, only the hostname changes.

6.1 Push the images¶

docker run -d --name lab06-registry --label lab06=1 -p 5001:5000 registry:2
Command What it does
docker run ... registry:2 start Docker's official registry image (version 2) in the background: a registry is itself just a container
↳ -p 5001:5000 the registry listens on 5000 inside the container; you reach it at localhost:5001
In [ ]:
fresh("lab06-registry")
sh(f"docker run -d --name lab06-registry --label {LABEL} -p 5001:5000 registry:2", check=True)
wait_for(f"http://{REG}/v2/")

Then tag both releases for the registry and push them:

Command What it does
docker tag reg-api:1.0.0 localhost:5001/reg-api:1.0.0 give the image a name that starts with the registry's address; that prefix tells Docker where to push it
docker push localhost:5001/reg-api:1.0.0 upload the image's layers to that registry
GET /v2/_catalog registry HTTP API: list all repositories
GET /v2/reg-api/tags/list registry HTTP API: list the tags of reg-api
In [ ]:
# TODO 6.1: tag reg-api:1.0.0 and reg-api:2.0.0 as {REG}/reg-api:<version>, then push both
# Example for a different image, myapp:0.1:
#   [f"docker tag myapp:0.1 {REG}/myapp:0.1", f"docker push {REG}/myapp:0.1"]
push_cmds = ["TODO"]
for c in push_cmds:
    sh(c, check=True)

# The registry has an HTTP API, just like Docker Hub or Artifact Registry
print(requests.get(f"http://{REG}/v2/_catalog").json())
print(requests.get(f"http://{REG}/v2/{IMAGE}/tags/list").json())

6.2 Pull on a "fresh machine"¶

Delete the local 1.0.0 image and pull it back. Note which layers Already exist, and the digest: the one reference that can never move.

Command What it does
docker image rm -f <image-id> delete the image by ID, which removes every tag pointing at it
↳ -f force, needed because several tags point at the same image
docker pull localhost:5001/reg-api:1.0.0 download the image from the registry; layers already on disk print Already exists
RepoDigests a field of docker image inspect: localhost:5001/reg-api@sha256:..., a hash of the image's content
docker tag localhost:5001/reg-api:1.0.0 reg-api:1.0.0 restore the short local name used later
In [ ]:
img_id = inspect_image(f"{IMAGE}:{V1}")["Id"]
sh(f"docker image rm -f {img_id}")
ok(inspect_image(f"{IMAGE}:{V1}") is None, "reg-api:1.0.0 is gone locally")
sh(f"docker pull {REG}/{IMAGE}:{V1}", check=True)
digest_ref = next(d for d in inspect_image(f"{REG}/{IMAGE}:{V1}")["RepoDigests"] if d.startswith(REG))
print("Immutable reference:", digest_ref)
sh(f"docker tag {REG}/{IMAGE}:{V1} {IMAGE}:{V1}")        # restore the local name

6.3 Push the code¶

Command What it does
git remote add <name> <url-or-path> register a remote repository under a short name (usually origin)
git push -u <remote> <branch> upload the branch; -u remembers the remote, so later a plain git push works
git push <remote> --tags upload the tags too (a normal push doesn't send them)
In [ ]:
REMOTE = Path(tempfile.gettempdir()) / "lab06-origin.git"
shutil.rmtree(REMOTE, ignore_errors=True)
sh(f'git init -q --bare "{REMOTE}"')                      # an empty "GitHub" on your own disk
sh("git remote remove origin", quiet=True)                # allows re-running this cell

# TODO 6.3: add the bare repo as remote `origin`, push branch main (set upstream with -u), then push all tags
# Example with a remote called `backup` and a branch called `dev`:
#   ["git remote add backup /tmp/backup.git", "git push -u backup dev", "git push backup --tags"]
git_push_cmds = ["TODO"]
for c in git_push_cmds:
    sh(c, check=True)
sh(f'git ls-remote "{REMOTE}"')                           # branch + both tags should be listed

Think about it: A deployment can pin reg-api:2.0.0 or reg-api@sha256:…. Why might a team pin the digest, and what's the downside for humans?


Part 7 · Compose¶

Instead of a long docker run -p ... -e ... --restart ..., describe the service once in compose.yaml. Compose fills in ${VARIABLES} from .env, so changing .env changes the deployment without touching the YAML.

Complete the three TODOs and keep the two lines already there.

Key What it does
services: the containers that make up this app (here, just one)
api: the service's name, used by docker compose commands
image: the image to run; ${API_TAG} is replaced with the value from .env
ports: a list of - "HOST:CONTAINER" entries, same as docker run -p
restart: restart policy; unless-stopped restarts the container after a crash or reboot, unless you stopped it yourself
container_name: a fixed container name, same as --name
labels: same as --label, so cleanup() finds it

Example for a different service. Keys under the service are indented by 4 spaces, and list items start with - .

services:
  web:
    image: registry.example.com/shop-web:${WEB_TAG}
    ports:
      - "${WEB_PORT}:3000"
    restart: always
In [ ]:
%%writefile compose.yaml
services:
  api:
    # TODO: image: localhost:5001/reg-api:${API_TAG}
    # TODO: ports: host ${HOST_PORT} -> container 8080
    # TODO: restart policy unless-stopped
    container_name: reg-api-live
    labels:
      - lab06=1

Compose reads compose.yaml and .env from the current folder.

Command What it does
docker compose config print compose.yaml with every ${VARIABLE} filled in from .env; a quick way to check your file
docker compose up create and start the services; a service whose configuration changed since last time gets its container recreated
↳ -d detached: run in the background
docker compose ps list this project's containers and their state
In [ ]:
sh("docker compose config")            # the resolved file: see how .env values were substituted
sh("docker compose up -d", check=True)
sh("docker compose ps")
print(wait_for("http://localhost:8000/health", timeout=60).json())
v = requests.get("http://localhost:8000/version").json()
print(f"serving app {v['app_version']} | model {v['model']['model_version']} | git {v['git_sha']} | host {v['hostname']}")

Part 8 · Deploy: live swap and rollback¶

v1 is live and v2 is in the registry. To release v2 you'll change one line in .env and let Compose replace the container, while a background poller hits /version every 0.1 s to count dropped requests.

8.1 Baseline¶

In [ ]:
sample = json.loads(Path("sample_request.json").read_text())
before = predict("http://localhost:8000", sample)
print("live now:", before["model_version"], before["predictions"])
print(f"offline metrics: v1 R²={meta_v1['test_r2']}, v2 R²={meta_v2['test_r2']}")

8.2 Swap to 2.0.0 under traffic¶

set_env("API_TAG", "2.0.0") rewrites the API_TAG= line in .env. Compose only notices when you apply the file again, with one of the commands from Part 7.

In [ ]:
poller, stats = start_poller("http://localhost:8000/version", seconds=12)
time.sleep(2)                                # let it record some healthy traffic first

set_env("API_TAG", "2.0.0")                  # the ONLY file we edit
print(Path(".env").read_text())

# TODO 8.2: apply the new .env: one Compose command that replaces the running container with 2.0.0
#           It's a single command string, and it's the same command that started the stack in Part 7.
swap_cmd = "TODO"
t0 = time.time()
sh(swap_cmd, check=True)
print(f"swap command took {time.time() - t0:.1f}s")
poller.join()
print(stats)

wait_for("http://localhost:8000/health")
after = predict("http://localhost:8000", sample)
print("live now:", after["model_version"], after["predictions"])

8.3 Bad predictions reported: roll back to 1.0.0¶

Same two steps as 8.2: change API_TAG in .env, then apply it with Compose.

In [ ]:
poller, stats = start_poller("http://localhost:8000/version", seconds=12)
time.sleep(2)

# TODO 8.3: roll back using only .env + one Compose command (no docker run, no rebuild)
#           Same two steps as 8.2: put the version you want back into API_TAG, then the same Compose command.
set_env("API_TAG", "TODO")
rollback_cmd = "TODO"
t0 = time.time()
sh(rollback_cmd, check=True)
print(f"rollback took {time.time() - t0:.1f}s")
poller.join()
print(stats)

wait_for("http://localhost:8000/health")
rolled = predict("http://localhost:8000", sample)
In [ ]:
# Check
ok(after["model_version"] == "2.0.0" and after["predictions"] != before["predictions"], "after the swap, v2 answers differently from v1")
ok(rolled["model_version"] == "1.0.0" and rolled["predictions"] == before["predictions"], "after rollback, predictions are identical to before the swap")
ok(sh("git check-ignore -q .env", quiet=True)[0] == 0, ".env is git-ignored, so swapping versions never touches your commits")

Think about it

  • How many requests failed during the swap and the rollback? Where did they go?
  • How could a release drop zero requests?
  • Why was the rollback a one-line change, with nothing rebuilt?

Where next? (optional reading)¶

The same image and compose.yaml run anywhere Docker runs:

Where How
Any VM or lab server copy compose.yaml + .env over, run docker compose up -d
Managed cloud containers (Cloud Run, App Runner, Azure Container Apps, Render, Fly.io) push the image to a registry, point the platform at it
Hugging Face Docker Spaces push a folder with the Dockerfile and model; the platform builds it

Three things to watch in the cloud:

  • CPU architecture: images built on Apple Silicon are arm64. Build with --platform linux/amd64, or you'll get exec format error.
  • Port: platforms inject $PORT; our CMD already uses it.
  • Secrets: use the platform's secret store, never the image or git.
Example: deploying to Google Cloud Run

Needs a GCP project with billing. Check the Cloud Run docs, as commands change.

gcloud auth login && gcloud config set project <PROJECT_ID>
gcloud services enable run.googleapis.com artifactregistry.googleapis.com
gcloud artifacts repositories create lab06 --repository-format=docker --location=asia-south1
gcloud auth configure-docker asia-south1-docker.pkg.dev

docker buildx build --platform linux/amd64 --build-arg APP_VERSION=2.0.0 --build-arg MODEL_SRC=models/v2 \
  -t asia-south1-docker.pkg.dev/<PROJECT_ID>/lab06/reg-api:2.0.0 --push .

gcloud run deploy reg-api --image=asia-south1-docker.pkg.dev/<PROJECT_ID>/lab06/reg-api:2.0.0 \
  --region=asia-south1 --allow-unauthenticated --max-instances=2

# delete it afterwards to avoid charges
gcloud run services delete reg-api --region=asia-south1
Command What it does
docker buildx build build with BuildKit, which can build for a different CPU than yours
↳ --platform linux/amd64 build for the CPU most cloud machines use
↳ --push push to the registry right after building

Going further: build the image in CI on every push, add Redis to compose.yaml, or run replicas on Kubernetes.

Troubleshooting
Symptom Likely cause and fix
Cannot connect to the Docker daemon Docker Desktop isn't running
port is already allocated an old container holds the port: run cleanup() or check docker ps
connection refused / reset from the host server bound to 127.0.0.1, wrong -p, or it crashed: check docker logs <name>
COPY failed: ... not found file missing, or excluded by .dockerignore
docker: 'compose' is not a docker command Docker is too old: update it (or use docker-compose)
Author identity unknown on git commit run the 5.1 setup cell, or git config user.email ...
Command What it does
docker compose down stop and remove the containers (and network) that docker compose up created
cleanup() remove every other lab container (see Part 4)

Images stay on disk. When you need the space back, list them with docker images and delete them with docker image rm -f <image-id>.

In [ ]:
# Clean up: stop everything this lab started
sh("docker compose down")
cleanup()