Dockerizing a Local LLM Chat Stack: One .env, Four Services, and Weights That Download Once
Put the Gemma chatbot into Docker: a single .env for the whole stack, weights from Kaggle Hub cached in model-cache, a backend image with the ML step on its own layer (about 9.4 GB), a three-stage Next.js image of about 300 MB, and a compose file for Redis, api, worker and frontend.
What you will learn
- Feed one .env file to the API, the Celery worker and the Next.js front end
- Order a backend Dockerfile so the heavy ML install is cached and only code changes rebuild
- Explain why NEXT_PUBLIC values are build arguments in a multi-stage Next.js image
- Run Redis, the API, the worker and the front end with compose, and keep model weights in a volume
Before you start
- Docker images, containers and volumes
- The local Gemma chatbot: FastAPI, Celery and Redis
So far each piece of our Gemma chatbot ran on its own, in its own terminal: Redis, the API, the Celery worker, the front end. With Docker, one command starts all of them, the same way on any machine. That makes every step after this one simpler.
If Docker itself is new, start with Docker essentials. For the general rule of when model weights should arrive in an image, see Docker for AI apps. This article is about one real stack.
The new layout
The project now has three folders, Django, FastAPI and Flask. Each is complete on its own, with its own Dockerfiles and env file. The front end is the same Next.js app in all three; only the backend changes. We use FastAPI. Inside it:
FastAPI/
backend/ API in app/, model code in gemma_core/
frontend/ the Next.js app
supabase/ the database migration
docker-compose.yml
.env.example
One .env for the whole stack
You copy .env.example to .env, and Docker hands it to the backend, the worker and the front end. Here's its shape, with values replaced by placeholders:
# ---- Supabase (Dashboard -> Project Settings -> API) ----
SUPABASE_URL=<your-project-url>
SUPABASE_SERVICE_ROLE_KEY=<your-service-role-key>
SUPABASE_JWT_SECRET=<your-jwt-secret>
# ---- Celery / Redis ----
# Inside Docker the broker is the "redis" service, not localhost.
CELERY_BROKER_URL=redis://redis:6379/0
CELERY_RESULT_BACKEND=redis://redis:6379/1
# ---- Model / inference ----
DEFAULT_MODEL_SLUG=gemma-3-1b-it
KAGGLE_API_TOKEN=
MODEL_PATH=
MODEL_SOURCE_URL=
USE_FAKE_ENGINE=true
# ---- Frontend (browser-safe) ----
NEXT_PUBLIC_SUPABASE_URL=<your-project-url>
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your-anon-key>
NEXT_PUBLIC_HCAPTCHA_SITE_KEY=<your-site-key>
NEXT_PUBLIC_SITE_URL=http://localhost:3000
NEXT_PUBLIC_BACKEND_URL=http://localhost:8000
Two things to notice. The broker address says redis, not localhost, because inside Docker containers find each other by their service name. And USE_FAKE_ENGINE=true gives a canned reply with no weights at all, which is handy for the first start. The front-end values all start with NEXT_PUBLIC_ because the browser is allowed to see them. The hCaptcha key in the example is hCaptcha's test key, which always passes.
Where the weights come from
Downloading from Hugging Face was giving trouble, so the code now uses Kaggle Hub. Sign in to Kaggle, accept the Gemma licence on its model page, and create an API token in your Kaggle settings. That token goes into KAGGLE_API_TOKEN.
gemma_core/download.py checks three places, in order. From its docstring:
"""
The weights are fetched **once** (the first time the app runs) and reused on
every start afterwards. Resolution order:
1. ``MODEL_PATH`` a local dir that already holds the weights: use it.
2. ``MODEL_SOURCE_URL`` download a .zip/.tar.gz (curl-style, from anywhere)
and extract it into the cache. Stdlib only.
3. Kaggle Hub the default source. Downloads the model via
``kagglehub`` and caches it under
``MODEL_CACHE_DIR``; later runs reuse the cache.
"""
The Kaggle Hub cache points inside model-cache in the backend folder. So the first start downloads the weights, and every start after that loads them from disk.
The prompt that did it
Role: A Python and Docker developer.
Context: Our chatbot, which downloads Gemma from Hugging Face.
Task: Switch the download to Kaggle Hub and cache the model so it's fetched only once. Dockerize the backend and the front end.
Format: The changed files, and a short note on how to run them.
Five files are new: two Dockerfiles, a .dockerignore for the front end, and two compose files, one for the whole stack and one for the backend alone. Read every file the tool writes. Here they are.
The backend Dockerfile
FROM python:3.11-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
WORKDIR /app
COPY requirements.txt requirements-ml.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
# For real inference (USE_FAKE_ENGINE=false), also install the ML stack
# (kagglehub + transformers + torch). This is what the Celery worker needs to
# download and run the Gemma weights.
RUN pip install --no-cache-dir -r requirements-ml.txt
# Copies the app AND its vendored ./gemma_core, nothing outside this folder.
COPY . /app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Notice the order. It copies only the two requirements files first and installs the small one. The heavy machine learning libraries, torch and transformers, get their own install step. Docker caches each step, so when you change your Python code only the last COPY runs again and those long installs are reused.
This image is big, about 9.4 GB, and nearly all of that comes from the ML step. One gap: there's no .dockerignore in the backend, so COPY . would also pick up a local .env or downloaded weights. A small ignore file fixes that.
The front-end Dockerfile: three stages
# ---- deps: install node_modules from the lockfile ----
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# ---- builder: compile the production bundle ----
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# NEXT_PUBLIC_* values are inlined into the browser bundle at BUILD time,
# so they must be provided as build args (docker-compose passes them from .env).
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
ARG NEXT_PUBLIC_HCAPTCHA_SITE_KEY
ARG NEXT_PUBLIC_SITE_URL
ARG NEXT_PUBLIC_BACKEND_URL
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL \
NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY \
NEXT_PUBLIC_HCAPTCHA_SITE_KEY=$NEXT_PUBLIC_HCAPTCHA_SITE_KEY \
NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL \
NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL
RUN npm run build
# ---- runner: minimal image that serves the standalone server ----
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]
- deps runs
npm ci, so it installs exactly what the lock file lists. - builder runs
npm run build. TheARGlines matter:NEXT_PUBLIC_values are written into the browser bundle while it builds. Change one, and you have to rebuild the front end, not only restart it. - runner takes just the standalone server and the static files. Standalone output is switched on in
next.config.ts, which is why this image is only about 300 MB. The build tools stay behind in the earlier stages.
The compose file
name: gemma-fastapi
services:
redis:
image: redis:7-alpine
ports:
- "6379:6379"
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
api:
build: ./backend
env_file:
- .env
ports:
- "8000:8000"
volumes:
- ./backend/model-cache:/app/model-cache # downloaded weights persist here
depends_on:
redis:
condition: service_healthy
worker:
build: ./backend
env_file:
- .env
command: celery -A app.core.celery_app.celery_app worker --loglevel=info
volumes:
- ./backend/model-cache:/app/model-cache
depends_on:
redis:
condition: service_healthy
frontend:
build:
context: ./frontend
args:
# NEXT_PUBLIC_* are baked into the browser bundle at build time.
NEXT_PUBLIC_SUPABASE_URL: ${NEXT_PUBLIC_SUPABASE_URL}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${NEXT_PUBLIC_SUPABASE_ANON_KEY}
NEXT_PUBLIC_HCAPTCHA_SITE_KEY: ${NEXT_PUBLIC_HCAPTCHA_SITE_KEY}
NEXT_PUBLIC_SITE_URL: ${NEXT_PUBLIC_SITE_URL}
NEXT_PUBLIC_BACKEND_URL: ${NEXT_PUBLIC_BACKEND_URL}
env_file:
- .env
ports:
- "3000:3000"
depends_on:
- api
Redis pings itself every five seconds. The api and the worker build the same backend image; the worker just runs a different command, the Celery worker. That's where the model runs, so there's no separate model container. Both wait for condition: service_healthy, and both mount model-cache so downloaded weights stay on your disk when containers stop.
Bring it up and check every part
cp .env.example .env
docker compose build
docker compose up -d
docker compose ps
The build makes three images, api, worker and frontend. The ML step is the slow one, so the first build takes a while. After up -d, Redis turns healthy first, then the others start. docker compose ps shows all four up: Redis healthy, the api on 8000, the frontend on 3000, and the worker with no port, because nothing outside needs to reach it.
Then check each part:
curlon/api/v1/healthreturns status ok, flavor fastapi./api/v1/conversationsreturns 401, "missing authorization header". Correct: chat history needs a signed-in user.- The worker log lists the task
chat.run_generation, shows it's connected to Redis, and says ready. With the fake engine it skips the model download. localhost:8000/docslists every endpoint;localhost:3000shows the Gemma ChatBot home page from its container.
To sign in and chat, put your Supabase values in .env. With USE_FAKE_ENGINE=false, the worker downloads Gemma from Kaggle the first time it starts. docker compose down stops and removes all four containers and the network. Anything in model-cache stays on disk.
Common mistakes
localhostas the broker inside Docker. Use the service name,redis.- Changing a
NEXT_PUBLIC_value and only restarting. It's baked in at build time. Rebuild the front end. - One
COPY .before the installs. Every code change would reinstall torch. - No backend
.dockerignore. Your.envand weights end up inside the image.
Quick recap
| Piece | What it does | Size or detail |
|---|---|---|
.env | Feeds api, worker and frontend | Broker is redis, not localhost |
| Backend image | API and worker, ML install on its own layer | About 9.4 GB |
| Front-end image | deps, builder, runner; standalone output | About 300 MB |
model-cache volume | Weights download once, survive restarts | Kaggle Hub by default |
| Compose | redis, api, worker, frontend | api and worker wait for a healthy Redis |
Try it yourself
Add a .dockerignore to the backend for .env and model-cache, rebuild, and check that .env is not inside the image (for example with docker compose run --rm api ls -a).
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)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.
