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.
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:
- A huge image. Several gigabytes, mostly libraries the service never uses. Every deploy pushes and pulls all of it.
- The model downloads when the container starts. So the first request waits.
- 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
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.txtbeforepip install, so that layer stays cached until the requirements change. useraddandUSER app: the service doesn't run as root.download_model.pyruns at build time. The weights become a layer of the image.HF_HOMEpoints 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
/healthevery 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
torchfrom 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
| Rule | Line that does it | Fixes |
|---|---|---|
| Slim base, CPU wheels | python:3.12-slim, torch==2.15.0+cpu | Huge image |
| Dependencies before code | COPY requirements.txt . then pip install | Slow rebuilds |
| Bake weights at build time | RUN python scripts/download_model.py | Download at start |
| Run offline | ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 | No internet, no start |
For images, containers and volumes from the ground up, see Docker Essentials.
Try it yourself
On a machine with Docker:
- Build both images with
docker compose build apianddocker compose --profile naive build naive, then compare their sizes withdocker images. - Run the tests with
docker run --rm --network none aie-s12l03-docsanswer tests. - Change one line of code, build again, and watch which layers say cached.
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.