Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
There's no test suite yet, so test the running Gemma chat app by hand in a fixed order: weights staged, images built, backend answers (and refuses with a reason), pages load, logs clean. Add a global exception handler so a dead Supabase shows 'ConnectError: connection refused', and end with a list of what still fails.
What you will learn
- Run a fixed, five-step manual check on a running FastAPI, Celery and React stack
- Stage model weights once into a mounted volume with a download script, before the build
- Add a catch-all exception handler so every 500 carries its reason to the UI
- Spot how the same checks look in the Django and Flask versions of the backend
Before you start
- Dockerizing the local LLM chat stack
- FastAPI routes and HTTPException
We built the Gemma chat app and put it into Docker. Now we test it, before we build anything more on top.
This project has no test suite yet, so there are no test files to run. Instead we test the running app by hand, in a fixed order, and whatever fails goes on a list for the next prompts.
1. Get the weights ready before the build
The app gets Gemma's weights from Kaggle Hub, so Kaggle needs to know who you are. requirements-ml.txt pins kagglehub 0.4.1 or newer, which is needed for the newer API token. On Kaggle, open your account settings, generate a new API token under API tokens (it's a single value, no username), and accept the Gemma licence on the model page once. Paste the token into .env on the KAGGLE_API_TOKEN line. Keep that file out of git.
Now, where should the download happen? If it happens during the Docker build or when the app starts, every rebuild can fetch the weights again, and a slow network can break the build. Better: download once into a local folder before anything runs. That folder is model-cache in the backend, and compose mounts it into both the API and the worker at /app/model-cache. A volume isn't rebuilt with the image, so the weights stay put.
We asked Claude Code for a script:
Role: A Python backend developer. Context: A FastAPI backend whose model settings are in the .env file. Task: Write a script that downloads the configured model into the backend's own model-cache folder, so the Docker build and the running app never have to download it. Format: One Python file in the backend folder, and the command to run it.
If it asks how to store the weights, pick a local download with a volume. Here's the core of download_model.py:
def main() -> int:
print(f" DEFAULT_MODEL_SLUG : {settings.default_model_slug}")
print(f" MODEL_CACHE_DIR : {settings.model_cache_dir}")
# ...
try:
path = ensure_model_available()
except Exception as exc: # noqa: BLE001 - surface the reason, fail the script
print(f"\nERROR: could not download / stage the model: {exc}", file=sys.stderr)
return 1
if not _has_model_files(path):
print(
f"\nERROR: no model files (config.json) found at {path} after staging. "
"If you set MODEL_PATH, make sure the weights actually live there.",
file=sys.stderr,
)
return 1
print(f"\nModel staged at: {path}")
return 0
It prints the model slug and cache folder, fetches the weights, checks that a config.json is really there, and returns 1 on any failure so the script fails clearly. Running it in the lecture went like this:
cd backend
python download_model.py # on Windows: py download_model.py
- First try: "kagglehub is not installed". The base requirements file doesn't have it; it lives in
requirements-ml.txt.pip install kagglehubinto the backend's virtual environment. - Second try: Kaggle answers 403, no permission to access the resource. That's what an empty token or an unaccepted licence gives you.
- Token added, licence accepted: it ends with
Model staged at:and a path insidemodel-cache.
While it downloads: make errors carry a reason
We gave the agent a second job, an audit: keep only user management, chat and chat history, keep it simple, and make sure every error reaches the UI with its reason. Three changes came back:
- An error handler in
main.py. - A React error page,
app/error.tsx, with the message and a Try again button instead of a blank screen. - A fix in
config.py: an emptyMODEL_CACHE_DIR=line used to leave the cache folder empty, so the weights landed outside the volume and downloaded again on every start. Now an empty value falls back to the default folder.
The handler changes how we test. Without it, an error no route catches comes back as a bare 500, and the front end can only say the request failed.
@app.exception_handler(Exception)
async def unhandled_exception_handler(_request: Request, exc: Exception) -> JSONResponse:
"""Turn any uncaught error into a JSON ``{detail: ...}`` 500."""
logger.exception("Unhandled error: %s", exc)
return JSONResponse(
status_code=500,
content={"detail": f"{type(exc).__name__}: {exc}"},
)
logger.exception sends the full traceback to the API log. The response carries the error's type and message in detail. On the React side, chat-api.ts reads it and throws it as the error message:
return data.detail || data.message || data.error || null;
2. Build and start
docker compose up --build
This build takes a while. The backend image installs PyTorch built for NVIDIA CUDA, and that download is large: the API image came out at 11.73 GB, and the worker uses the same image. The front end is about 300 MB, Redis much smaller. Check your disk space first. The image targets NVIDIA cards; with another kind of GPU the GPU path won't work as it is (the GPU gets its own step later). Four containers come up: Redis healthy on 6379, the API on 8000, the worker running, the front end on 3000.
3. The backend says no, with a reason
Open localhost:8000/docs. Swagger lists every route.
| Request | Answer |
|---|---|
| GET health | 200, status ok, flavor fastapi |
| conversations, no token | 401, missing authorization header |
| conversations, wrong secret | 401, signature verification failed |
| conversations, old token | 401, token has expired |
| POST chat, empty body | 422, names the two missing fields: content and model_slug |
Now one that fails on purpose. Point the Supabase address in .env at a place where nothing runs, and call get models with Try it out. You get a 500, but the body says ConnectError: connection refused. That's the handler at work, and the API log has the full traceback. Here, the backend can't reach Supabase, and the message tells you where to look.
4. The React pages
localhost:3000 loads. The login page has Continue with Google, email and password, and the hCaptcha box, which says it's for testing only because .env still has the public test site key. Open /chat signed out, and the middleware sends you to login with redirectTo=/chat. Pages load, the protected page stays protected.
5. The logs
docker compose logs frontend
docker compose logs api
docker compose logs worker
Front end: Next.js ready on port 3000. API: Uvicorn running on 8000, plus the unhandled error we just caused. The worker log is the one to watch. With the real engine on and no token, the worker tries to fetch the model, gets the same 403, prints a warning, and still says ready. So the worker looks fine and the problem only shows on the first chat message. Read the logs; don't trust "ready" on its own.
The fix list
- Front-end URLs. The backend URL, the Supabase URL and the hCaptcha site key are baked into the browser code at build time. Wrong values send you to the wrong place, and changing
.envalone doesn't help. You have to rebuild. - hCaptcha. Still on the test key.
- Chat. The message goes out, the page keeps polling, no reply comes back. One likely cause is the one in the worker log: a model that never loaded.
Those get fixed in the next round.
The same checks with Django or Flask
The order stays the same, and the React pages and model download work the same way. What changes is in the backend.
| FastAPI | Django | Flask | |
|---|---|---|---|
| Swagger | /docs | /api/schema/swagger-ui (drf-spectacular) | not covered in the lecture |
| Built-in checks | none yet | manage.py test (0 tests, OK) and manage.py check (no issues) | create_app() gives a test client; five pytest checks pass in about 3 s |
| No token | 401, missing authorization header | 401, authentication required | 401 |
| Empty chat body | 422 | 400 from the serializer, both fields named | 422, Marshmallow lists both fields under errors |
| Reason field | detail | uncaught errors: HTML page (no handler) | message |
| Uncaught error | JSON 500 via the handler | 500 as text/html; read the API log | JSON 500 once you add the handler below |
In Django, with debug on (the project default), an uncaught error returns Django's HTML error page; with debug off it's just "server error". Keep debug off anywhere but your own machine. Because chat-api.ts can't read JSON from an HTML page, the UI only shows "chat request failed" and the status. To get the reason into the UI, Django REST framework lets you set your own exception handler in settings.py.
In Flask, app/__init__.py has a create_app() factory; wsgi.py calls it once and Gunicorn runs it with two workers. Its image installs only the base requirements (the ML line is commented out) and is about 290 MB, against 11.73 GB for FastAPI. The lecture adds a handler inside create_app():
@app.errorhandler(Exception)
def handle_unexpected_error(exc):
if isinstance(exc, HTTPException):
return exc
logger.exception("Unhandled error: %s", exc)
return jsonify(message=f"{type(exc).__name__}: {exc}"), 500
HTTP exceptions pass through, so the 401s and the 422 don't change. Anything else is logged and returned as a 500 with a message, and the same call now says connect error, connection refused. The React side needs no change, because it reads detail, then message.
Common mistakes
- Downloading weights inside the build. Every rebuild risks fetching gigabytes again.
- Trusting "ready" in the worker log. It can be ready with no model loaded.
- A bare 500. Without a handler, the UI can't tell a dead database from a bad request.
- Debug on in Django outside your machine. The HTML error page shows internals.
Quick recap
| Check | What passing looks like |
|---|---|
| Weights | Model staged at a path in model-cache |
| Build | four containers, Redis healthy |
| Backend | 200 on health; 401 and 422 with reasons; 500 with detail |
| Pages | login loads, /chat redirects when signed out |
| Logs | no surprise warnings, especially in the worker |
Try it yourself
Pick one of the three issues on the list, write a prompt to fix it, rebuild, and check it again in the same order.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)