TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Docker Images for Model Services

Docker Images for Model Services

A model service is ordinary software with three unusual properties: its dependencies are huge (numerical libraries, sometimes a deep-learning framework of several hundred megabytes), it carries a large binary artifact (the model), and it has to load that artifact before it can answer anything. A container image is how almost every team ships it, to Kubernetes, to a managed platform or to a single VM. This lesson is about what makes a good image for a model, not about Docker itself: for that, the Docker course covers Dockerfiles, the build cache, multi-stage builds, image size, users and security and health checks.

What goes into a model image

base: python:3.13-slimchanges: rarely (security updates) dependencies from a lock filechanges: when a pin changes model file (or none: pulled at start)changes: every model release service codechanges: every commit final image, top layer changes most often builder stagecompilers, headers, pip cachediscarded; only the venv is copied runtime settingsUSER non-root, read-only filesHEALTHCHECK / readiness endpointlabels: model version, git committhreads = CPU limit

A Dockerfile that puts these together, for the FastAPI service of FastAPI for production with an ONNX model (shown, not run):

dockerfile
# syntax=docker/dockerfile:1
# ---- builder: compilers and pip live here only ----
FROM python:3.13-slim AS builder
RUN python -m venv /opt/venv
ENV PATH=/opt/venv/bin:$PATH
COPY requirements.lock .
RUN pip install --no-cache-dir --require-hashes -r requirements.lock

# ---- runtime ----
FROM python:3.13-slim
RUN useradd --create-home --uid 10001 app
COPY --from=builder /opt/venv /opt/venv
ENV PATH=/opt/venv/bin:$PATH \
    PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 \
    OMP_NUM_THREADS=2 MODEL_PATH=/models/risk-model.onnx
WORKDIR /app
COPY --chown=app models/risk-model.onnx /models/
COPY --chown=app app/ /app/
USER app
ARG GIT_SHA=unknown
LABEL org.opencontainers.image.revision="$GIT_SHA" \
      ai.example.model.name="risk-model" ai.example.model.version="7"
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=2s --start-period=30s \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/ready')"
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]

The model-specific decisions, one by one:

  • A slim base, and CPU-only wheels. python:3.13-slim (Debian, glibc) works with the manylinux wheels of NumPy, scikit-learn and ONNX Runtime; Alpine uses musl and often forces slow source builds. The biggest trap is PyTorch: on Linux the default pip install torch pulls a CUDA build with several gigabytes of NVIDIA libraries. A CPU service should install from PyTorch's CPU wheel index (--index-url https://download.pytorch.org/whl/cpu, versions ending in +cpu), or better, not install PyTorch at all and serve an ONNX export with ONNX Runtime. A GPU service starts from a CUDA runtime base image whose CUDA version matches the framework's wheels (see GPU inference).
  • Pinned, hashed dependencies. The model was trained and tested with exact library versions; a scikit-learn minor release can refuse or silently change a pickled model (pickle and joblib). Install from a lock file with every package pinned with == and, ideally, --require-hashes (hash pinning). Keep test tools out of the runtime image.
  • Multi-stage. Anything needed only to build (compilers, -dev headers, pip's cache) stays in the builder; the runtime copies the finished virtual environment.
  • Layer order. Things that change rarely go first. Code changes on every commit, so it is copied last.
  • Non-root, no secrets. Run as an unprivileged user (USER and EXPOSE), never bake credentials into a layer (they stay in the image history), keep a .dockerignore so that notebooks, datasets and .env files never enter the build context.
  • Threads match the CPU limit. NumPy, ONNX Runtime and PyTorch start one thread per host core by default. In a container limited to 2 CPUs on a 64-core node, that is 64 threads fighting over 2 cores per worker process, which can multiply latency. Set OMP_NUM_THREADS (and the runtime's own setting, such as ONNX Runtime's intra_op_num_threads) so that workers times threads is about the CPU limit (resource limits).
  • Health and identity. A readiness endpoint that answers only after the model is loaded, used by HEALTHCHECK here and by Kubernetes probes in a cluster. Labels with the model name, model version and git commit make every running container traceable to a registry entry.

Checking a requirements file

A small linter for the rules above, the kind of check that runs in CI before docker build. It flags unpinned packages, the default (CUDA) PyTorch wheel, test tools and a git dependency that points at a branch, and computes a fingerprint of the pins that can serve as a cache key or an image label.

python · try it yourself
import hashlib
import re

requirements = """\
fastapi==0.118.0
uvicorn[standard]==0.37.0
numpy==2.2.5
scikit-learn>=1.6
pandas
onnxruntime==1.31.1
torch==2.14.1
pytest==8.4.2
git+https://github.com/example/featurelib.git@main
"""

DEV_ONLY = {"pytest", "jupyter", "ipykernel", "black", "ruff", "mypy"}
problems, pinned = [], []
for line in requirements.splitlines():
    line = line.strip()
    if not line or line.startswith("#"):
        continue
    if line.startswith("git+"):
        ref = line.rsplit("@", 1)[-1]
        if not re.fullmatch(r"[0-9a-f]{40}", ref):
            problems.append(f"{line}: git ref '{ref}' is a branch, pin a full commit hash")
        continue
    m = re.fullmatch(r"([A-Za-z0-9_.-]+)(\[[^\]]+\])?\s*(==|>=|<=|~=)?\s*(\S+)?", line)
    name, op, version = m.group(1).lower(), m.group(3), m.group(4)
    if op != "==":
        problems.append(f"{line}: not pinned (use ==)")
    elif name == "torch" and "+cpu" not in version:
        problems.append(f"{line}: default wheel; on Linux use the CPU-only index for a CPU service")
    if name in DEV_ONLY:
        problems.append(f"{line}: test/dev tool in the runtime image")
    if op == "==":
        pinned.append(f"{name}=={version}")

print(f"{len(problems)} problems:")
for p in problems:
    print(" -", p)
digest = hashlib.sha256("\n".join(sorted(pinned)).encode()).hexdigest()[:12]
print(f"\nfingerprint of the {len(pinned)} pinned lines: {digest} (changes whenever any pin changes)")
5 problems:
 - scikit-learn>=1.6: not pinned (use ==)
 - pandas: not pinned (use ==)
 - torch==2.14.1: default wheel; on Linux use the CPU-only index for a CPU service
 - pytest==8.4.2: test/dev tool in the runtime image
 - git+https://github.com/example/featurelib.git@main: git ref 'main' is a branch, pin a full commit hash

fingerprint of the 6 pinned lines: 93e73c74e672 (changes whenever any pin changes)

Five problems in nine lines: two unpinned packages (>=1.6 and a bare pandas would install whatever is newest on the day of the build), the default PyTorch wheel, a test tool, and a git dependency on the moving branch main. Each of these means that rebuilding the same Dockerfile next month can produce a different image. The fingerprint 93e73c74e672 covers the six pinned lines; any change of a pin changes it.

Layer order and the build cache

Docker rebuilds a layer when its inputs change, and then every layer after it. The simulation below uses assumed layer sizes (820 MB of model, 310 MB of installed packages) and two Dockerfiles: a naive one that copies the whole project and then installs, and the ordered one from above.

python · try it yourself
# Each layer: (instruction, size in MB, files it reads). A layer is rebuilt when a file it reads
# changed or when any layer above it was rebuilt; all later layers then miss the cache too.
naive = [
    ("FROM python:3.13-slim",               0, set()),          # base: pulled once, cached on every node
    ("COPY . /app",                         820, {"app.py", "requirements.txt", "model.onnx"}),
    ("RUN pip install -r requirements.txt", 310, set()),
]
ordered = [
    ("FROM python:3.13-slim",               0, set()),
    ("COPY requirements.txt .",             0, {"requirements.txt"}),
    ("RUN pip install -r requirements.txt", 310, set()),
    ("COPY model.onnx /app/",               820, {"model.onnx"}),
    ("COPY app.py /app/",                   0.02, {"app.py"}),
]

def rebuild(layers, changed):
    dirty, rebuilt = False, []
    for instr, size, reads in layers:
        dirty = dirty or bool(reads & changed)
        if dirty:
            rebuilt.append((instr, size))
    return rebuilt

for change in ({"app.py"}, {"model.onnx"}, {"requirements.txt"}):
    print(f"changed: {', '.join(sorted(change))}")
    for name, layers in (("naive  ", naive), ("ordered", ordered)):
        r = rebuild(layers, change)
        print(f"  {name}: {len(r)} layers rebuilt, {sum(s for _, s in r):7.2f} MB to build and push"
              f"{'  (pip install reruns)' if any('pip' in i for i, _ in r) else ''}")
changed: app.py
  naive  : 2 layers rebuilt, 1130.00 MB to build and push  (pip install reruns)
  ordered: 1 layers rebuilt,    0.02 MB to build and push
changed: model.onnx
  naive  : 2 layers rebuilt, 1130.00 MB to build and push  (pip install reruns)
  ordered: 2 layers rebuilt,  820.02 MB to build and push
changed: requirements.txt
  naive  : 2 layers rebuilt, 1130.00 MB to build and push  (pip install reruns)
  ordered: 4 layers rebuilt, 1130.02 MB to build and push  (pip install reruns)

With the naive order, every change, even one line of app.py, invalidates COPY . /app, reinstalls all packages and pushes 1130 MB. The ordered Dockerfile rebuilds 0.02 MB for a code change and 820.02 MB for a new model; only a change of requirements.txt rebuilds everything. Faster builds are nice; the bigger gain is that nodes which already hold the lower layers pull only the changed top layers when a new version rolls out.

Model in the image, or pulled at start?

Baking the model into the image makes the image the unit of deployment: one digest pins code, dependencies and model together, a rollback is an image rollback, and the container needs no credentials for a model store at start-up. Pulling the model at start (from object storage or the model registry, often by an init container into a shared volume) keeps one image for many models and lets you change the model without a rebuild, but start-up now depends on another service, and the image digest alone no longer says what is running. Start-up time, with assumed bandwidths, for a small model and for a 14 GB language model:

python · try it yourself
# Time until a new replica is ready, on a node that has never pulled this image.
# Assumed numbers (compressed MB and MB/s); replace them with measurements from your platform.
runtime_image = 380          # python slim + onnxruntime + fastapi
registry_bw = 120            # node <- container registry
store_bw = 200               # node <- object storage (S3, GCS, ...), parallel download

for model_mb, load_s in ((820, 6), (14000, 40)):     # a small model, and a 7B LLM in 16-bit
    baked = (runtime_image + model_mb) / registry_bw + load_s
    pulled = runtime_image / registry_bw + model_mb / store_bw + load_s
    print(f"model {model_mb:5d} MB: baked into the image {baked:6.1f} s, pulled at start {pulled:6.1f} s")
    print(f"               node has the image cached: baked {load_s:4.1f} s, pulled {model_mb / store_bw + load_s:6.1f} s")
model   820 MB: baked into the image   16.0 s, pulled at start   13.3 s
               node has the image cached: baked  6.0 s, pulled   10.1 s
model 14000 MB: baked into the image  159.8 s, pulled at start  113.2 s
               node has the image cached: baked 40.0 s, pulled  110.0 s

For the 820 MB model the difference is a few seconds (16.0 s baked, 13.3 s pulled on a cold node) and with a cached image baking wins (6.0 s against 10.1 s). For 14 GB the picture changes: a 14 GB image takes 159.8 s to become ready on a cold node, pulling it in parallel from object storage 113.2 s, and every new node needs the full download either way. Large models are therefore usually pulled, cached on the node (a local volume or a node-level cache) or streamed, while small models are baked in. Whatever you choose, record the model version in the container's environment and expose it on an endpoint.

Pitfalls

  • Shipping the CUDA wheel to CPU nodes: gigabytes of unused libraries, slower pulls and a larger attack surface. Check the image size in CI.
  • Unpinned or unhashed dependencies: two builds of the same commit produce different images; a model may stop loading.
  • Running as root, and secrets or training data in the build context.
  • Thread oversubscription: one thread per host core in every worker of every container. Set the thread count explicitly.
  • A health check that only says "the process is up": traffic arrives before the model is loaded. Check readiness on an endpoint that knows the model is ready.
  • Unscanned images: scan them and record an SBOM (image scanning, SBOM in CI).

Practice

  1. Your image is 4.1 GB, and pip list inside it shows nvidia-cublas-cu12 and friends, but the service runs on CPU nodes. What happened and how do you fix it?
Answer

pip install torch from PyPI installed the CUDA build and its NVIDIA library wheels. Install from the CPU index (--index-url https://download.pytorch.org/whl/cpu, pinned torch==<version>+cpu), or export the model to ONNX and drop PyTorch from the serving image.

  1. A container with a 2-CPU limit runs 4 uvicorn workers on a 32-core node, and p99 latency is far worse than in local tests. Name a likely cause and a fix.
Answer

Each worker's numerical library starts about 32 threads, so 128 threads compete for 2 CPUs and the kernel throttles the container. Set OMP_NUM_THREADS=1 (or the runtime's thread option) and use 2 workers, so that workers times threads matches the limit; then measure.

  1. In the layer simulation, add a layer RUN python warmup.py after COPY app.py that compiles the model for the CPU (300 MB of cache files). What does a code change cost now, and how could you avoid it?
Answer

It reads files from app.py's layer and follows it, so every code change also reruns the warm-up and pushes 300 MB more. Place the warm-up right after the model layer (it depends only on the model and the runtime), before copying the code.

Test yourself

Why should the service code be copied after the dependencies and the model in a Dockerfile?

  1. It changes most often, and every layer after a changed one is rebuilt
  2. Docker requires code to be the last instruction
  3. It makes the image smaller
  4. So that the code runs as root

Which is a real advantage of baking the model into the image rather than pulling it at start?

  1. One image digest pins code, dependencies and model, and start-up needs no model store
  2. The image is smaller
  3. New models need no rebuild
  4. It is faster for 14 GB models on cold nodes

A CPU-only service installs torch with a plain pip install on Linux. What is the main problem?

  1. It gets the CUDA build with gigabytes of unused GPU libraries
  2. PyTorch cannot run on CPU
  3. pip refuses to install it
  4. The model becomes non-deterministic

What should a model container's health check test?

  1. That the model is loaded and the service can answer
  2. That the Python process exists
  3. That the image is small
  4. That the GPU is hot