Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. AI System Design

Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline

An AI service image goes wrong in three ways: it's huge, it downloads the model when it starts, and without internet it can't start at all. All three come from one question: when do the weights arrive? Fix it with a slim base, CPU-only torch, pinned packages, weights baked in at build time and HF_HUB_OFFLINE.

Chaand Sheikh

·27 November 2026AI System Design

What you will learn

  • Explain the three failures of a naive AI image: size, download at start, no internet no start
  • Order Dockerfile layers so dependencies and weights stay cached and only the code rebuilds
  • Download only the weight files the library needs at build time, then set HF_HUB_OFFLINE
  • Install the CPU-only PyTorch wheel with pinned requirements

Before you start

  • Containerising a Model API: A Dockerfile for FastAPI
  • FastAPI for AI Services

A Dockerfile for a plain web API is well-trodden ground, and Containerising a Model API walks through one line by line. An AI service adds a problem most people get wrong: the model weights. In this article we package a help-centre RAG service that uses a small local embedding model, and we answer one question properly. The weights are just a file. When does that file arrive?

The project is docs-answer, now with an embedding retriever. It runs with a stand-in test model, so you need no key. One thing to say plainly: Docker wasn't running on the machine where the lecture's outputs were captured. So you'll see the Dockerfiles and the commands, and every console output here comes from running the same code without Docker. There are no image sizes in this article because none were measured.

Works on my machine

Three things usually go wrong with an AI image:

  1. A huge image. Several gigabytes, mostly libraries the service never uses. Every deploy pushes and pulls all of it.
  2. The model downloads when the container starts. So the first request waits.
  3. No internet, no start. If the server has no internet, or the model site is down, the container can't start at all.

All three come from the weights arriving at the wrong time. The answer we want is at build time, not when the container starts.

Why the service needs a model at all

python demo.py weights
python demo.py retrievers
HF_HOME=(default: ~/.cache/huggingface)  HF_HUB_OFFLINE=0
sentence-transformers/all-MiniLM-L6-v2: 92 MB in ~\.cache\huggingface\hub\models--sentence-transformers--all-MiniLM-L6-v2

embedding model loaded and 27 chunks encoded in 27.1s
Can I get my money back?
  keyword     returns-and-refunds.md - When you get your refund (3.123)
  embeddings  returns-and-refunds.md - When you get your refund (0.399)
My parcel has not turned up
  keyword     shipping.md - Changing the delivery address (3.835)
  embeddings  order-tracking.md - My parcel is late (0.628)
I forgot my login
  keyword     password-reset.md - Locked out after too many attempts (2.136)
  embeddings  password-reset.md - Reset a forgotten password (0.557)
Do you deliver to Toronto?
  keyword     nothing found
  embeddings  shipping.md - International shipping (0.496)

The model is all-MiniLM-L6-v2, 92 MB in the Hugging Face cache folder. Loading it and encoding the 27 help-centre chunks took 27.1 s on that machine. For questions in other words, the embeddings find the right page: "My parcel has not turned up" finds "My parcel is late", and "Do you deliver to Toronto?" finds international shipping where the keyword index finds nothing. So the model earns its place. But now it's a file, and loading it takes time.

The first attempt

# The first attempt. It builds and it runs, but look at what it costs:
#   - python:3.12 (the full Debian image with compilers) instead of python:3.12-slim
#   - COPY . . before pip install: change one line of code and every package installs again
#   - nothing pinned, default index: the CUDA build of PyTorch, gigabytes the CPU never uses
#   - the embedding weights download when the container STARTS: slow first start, and no internet = no start
#   - runs as root, no healthcheck
# Build it: docker compose --profile naive build naive
FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r docker/requirements-naive.txt
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

It builds and it runs. The full python:3.12 image brings compilers we don't need. Copying all the code before pip install means one changed line reinstalls every package. Unpinned requirements on the default index bring the CUDA build of PyTorch on Linux, gigabytes of GPU libraries on a CPU server. And there's no step for the model, so the weights download when the container starts: failures two and three.

Slow, stable things at the bottom

Layer order for an AI image 5. code (COPY . .), changes daily 4. model weights, at build time 3. user app, /opt/hf cache folder 2. pinned packages, CPU-only torch 1. python:3.12-slim rebuilds on a code edit cached, reused build after build
Each Dockerfile line makes a layer, and Docker reuses a layer until something under it changes.

At the bottom, the slim base. Then the packages: they change rarely, so this big layer is reused build after build. Then a normal user that isn't root, and a folder for the model. Then the weights, which are now part of the image, so the container never downloads them. And at the very top, our code, the thing we change every day. Edit one line of code and only the top layer rebuilds.

The fixed Dockerfile

# docs-answer, stage 3: an image built for an AI service. No API key needed: the stand-in test model answers.
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PYTHONIOENCODING=utf-8 HF_HOME=/opt/hf
WORKDIR /app

# 1. Dependencies first (pinned, CPU-only torch). Docker reuses this layer until requirements.txt changes.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 2. A user that is not root, and a cache folder it owns.
RUN useradd --create-home app && mkdir -p /opt/hf && chown app /opt/hf
USER app

# 3. The model weights, baked in at BUILD time. Only the files sentence-transformers needs.
COPY --chown=app app/__init__.py app/config.py app/
COPY --chown=app scripts/download_model.py scripts/
RUN python scripts/download_model.py

# 4. The code last: editing it rebuilds only this small layer. From here on, never touch the internet.
COPY --chown=app . .
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=5 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
ENTRYPOINT ["python", "demo.py"]
  • python:3.12-slim: the same Python on a much smaller base.
  • Only requirements.txt before pip install, so that layer stays cached until the requirements change.
  • useradd and USER app: the service doesn't run as root.
  • download_model.py runs at build time. The weights become a layer of the image. HF_HOME points the Hugging Face cache at /opt/hf, a folder the app user owns. Only the two files the script imports are copied before it, so a code edit doesn't throw the weights layer away.
  • The code is copied last.
  • HF_HUB_OFFLINE=1: from here on, the libraries never try to reach the internet. If a file is missing, you find out at build time, where you can see it, not in production.
  • A healthcheck calls /health every 10 seconds and marks the container healthy or not.

And .dockerignore keeps your .env file, with its keys, out of the image.

Where the size really goes: PyTorch

# CPU-only PyTorch: the default Linux wheel brings the CUDA libraries, several GB the CPU never uses.
--extra-index-url https://download.pytorch.org/whl/cpu
torch==2.15.0+cpu
sentence-transformers==6.2.0
transformers==5.22.2
huggingface_hub==2.4.0
numpy==2.5.4
fastapi==0.162.0
uvicorn[standard]==0.54.0
pydantic==2.14.3
pydantic-settings==2.16.1
httpx==0.28.1
pytest==9.2.0
# only used when OPENAI_API_KEY is set
openai==3.49.0

The extra index is the PyTorch CPU index, and torch==2.15.0+cpu is the build without the CUDA libraries. This one change is usually the biggest saving in the whole image. Every other package is pinned too, so the same build gives the same image next month.

Only the files you need

"""Download the embedding model's weights into the Hugging Face cache. The Dockerfile runs this at BUILD time,
so the weights are a layer of the image and the container never downloads anything when it starts."""
import sys
import time
from pathlib import Path

from huggingface_hub import snapshot_download

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.config import settings  # noqa: E402

NEEDED = ["modules.json", "config.json", "config_sentence_transformers.json", "sentence_bert_config.json",
          "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "vocab.txt",
          "model.safetensors", "1_Pooling/config.json"]       # not the ONNX / OpenVINO / PyTorch .bin copies

start = time.perf_counter()
folder = Path(snapshot_download(settings.embed_model, allow_patterns=NEEDED))
size = sum(f.stat().st_size for f in folder.rglob("*") if f.is_file())
print(f"{settings.embed_model}: {size / 1e6:.0f} MB in {folder} ({time.perf_counter() - start:.1f}s)")

NEEDED lists only what sentence-transformers needs: the config, the tokenizer and model.safetensors. The model repo also holds other copies of the same weights, for ONNX and OpenVINO, and allow_patterns keeps them out. The script prints the size, so you see it in the build log.

Offline, and checked

$env:HF_HUB_OFFLINE=1; python scripts/download_model.py
python -m pytest tests/test_image.py -v
$env:HF_HUB_OFFLINE=1; $env:TRANSFORMERS_OFFLINE=1; python demo.py tests
sentence-transformers/all-MiniLM-L6-v2: 92 MB in ~\.cache\huggingface\hub\models--sentence-transformers--all-MiniLM-L6-v2\snapshots\1110a243fdf4706b3f48f1d95db1a4f5529b4d41 (0.0s)

tests/test_image.py::test_slim_base_and_cpu_only_torch PASSED          [ 20%]
tests/test_image.py::test_every_requirement_is_pinned PASSED           [ 40%]
tests/test_image.py::test_dependencies_then_weights_then_code PASSED   [ 60%]
tests/test_image.py::test_runs_offline_and_not_as_root PASSED          [ 80%]
tests/test_image.py::test_secrets_stay_out_of_the_image PASSED         [100%]
============================== 5 passed in 0.10s ==============================

.............. [100%]
14 passed in 12.72s

With HF_HUB_OFFLINE set, the download script finds all 92 MB in the cache in 0.0 s: nothing was downloaded. The five image tests read the Dockerfile and requirements and check the rules: slim base and CPU torch, every version pinned, dependencies then weights then code, offline and not root, and no secrets in the image. All fourteen tests pass with the offline flags on. In Docker you'd run the same tests with docker run --rm --network none aie-s12l03-docsanswer tests; if the image needed the internet, they would fail.

Common mistakes

  • Letting the library download weights on first use. It works on your laptop, then a server with no internet can't start.
  • Installing torch from the default index on a CPU server. You ship GPU libraries nobody calls.
  • Copying the whole project before the weights step. Every code edit invalidates the weights layer and downloads them again.
  • Downloading the whole model repo. ONNX and OpenVINO copies of the same weights ride along for nothing.

Quick recap

RuleLine that does itFixes
Slim base, CPU wheelspython:3.12-slim, torch==2.15.0+cpuHuge image
Dependencies before codeCOPY requirements.txt . then pip installSlow rebuilds
Bake weights at build timeRUN python scripts/download_model.pyDownload at start
Run offlineENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1No internet, no start

For images, containers and volumes from the ground up, see Docker Essentials.

Try it yourself

On a machine with Docker:

  1. Build both images with docker compose build api and docker compose --profile naive build naive, then compare their sizes with docker images.
  2. Run the tests with docker run --rm --network none aie-s12l03-docsanswer tests.
  3. Change one line of code, build again, and watch which layers say cached.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 79 of 89

Previous
Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
Next post
Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed

When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.

Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves

A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.

Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys

Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.

A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue

A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.

On this page

  • Works on my machine
  • Why the service needs a model at all
  • The first attempt
  • Slow, stable things at the bottom
  • The fixed Dockerfile
  • Where the size really goes: PyTorch
  • Only the files you need
  • Offline, and checked
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.