Chapter 8

Deploying and running it

Putting the backend next to your site on your own server, one command at a time: DNS, Docker, nginx, HTTPS, then switching the ✦ button on. After that, the day-to-day of running an AI feature on free tiers.

The production shape

visitor ──https──▶ nginx ─┬─ aminehajji.dev        → static files (~/apps/my-portfolio/dist), as today
                          └─ api.aminehajji.dev    → 127.0.0.1:8000 → Docker container (FastAPI + models)
                                                                       └─ volume: SQLite history
container ──https──▶ Groq, Gemini, Cloudflare, OpenRouter   (language models, in LLM_MODELS order)
container ──https──▶ aminehajji.dev/knowledge.json          (content, on startup / reindex)

Speech, embeddings and search run inside the container. Only the language model call leaves your server.

Before you start

Plan about an hour, mostly waiting for the first build. Open two terminal windows and keep them open until the end. Every command box below says which window it goes in:

Label on the boxWhere to type it
Your PC · PowerShellA normal PowerShell window on your computer.
ServerA second PowerShell window where you've typed ssh zindivps. The prompt looks like ubuntu@…:~$. Everything you type there runs on the VPS.

Paste one box at a time with its Copy button, then compare the result with You should see before moving on. Lines starting with # are comments: both shells ignore them, so you can paste them too.

Recommended first

Do steps 1 to 3 of your private server notes (my-portfolio/SERVER-TODO.md) first: SSH keys only, apps that start on boot, pending updates. The assistant works without them, but they make the server safer before you add something new to it.

Deploy, step by step

Step 1 · Check it works on your PC

The tests use fake models, so this takes a few seconds and needs no internet.

cd C:\dev\portfolio-assistant
.venv\Scripts\python -m pytest -q

You should see: 20 passed on the last line. If something fails, stop here and fix it first: the server would fail the same way.

Step 2 · Add the DNS record (OVH)

api.aminehajji.dev must point to the same server as the main site. Your domain's DNS is at OVH.

  1. Open the OVHcloud Control Panel and log in.
  2. Go to Web Cloud → Domain names → aminehajji.dev → the DNS zone tab.
  3. Click Add an entry → choose A.
  4. Subdomain: api · Target: 164.132.85.214 (the VPS: the same target as the existing evmirror entry). Leave the TTL as it is → Next → Confirm.

It can take from a few minutes to an hour to work everywhere. Carry on with the next steps meanwhile; you'll check it before step 7:

nslookup api.aminehajji.dev

You should see: Address: 164.132.85.214 at the end. "Non-existent domain" means it isn't there yet: wait a few minutes and try again.

Step 3 · Install Docker on the server

Open your second window and connect: ssh zindivps. Then:

sudo apt update
sudo apt install -y docker.io docker-compose-v2 docker-buildx
# let your user run docker without sudo
sudo usermod -aG docker ubuntu
exit

The group change only applies to new logins, which is why the last line disconnects you. Connect again with ssh zindivps, then:

docker compose version
docker run --rm hello-world

You should see: Docker Compose version 2.…, then Hello from Docker! in the second command's output. permission denied … docker.sock means you didn't reconnect: type exit, then ssh zindivps again.

Step 4 · Get the backend on the server (git clone)

The code is on GitHub in a private repository (amine-a11/portfolio-assistant), so the server needs permission to download it. You give it a deploy key: an SSH key that lives on the server and can only read this one repository. If the server were ever broken into, the key couldn't touch your other repos or change this one.

4a. Create the key on the server. The second command gives it a short name, github-portfolio-assistant, so git knows which key to use for this repository.

ssh-keygen -t ed25519 -N "" -C "zindivps portfolio-assistant" -f ~/.ssh/portfolio-assistant
cat >> ~/.ssh/config <<'EOF'
Host github-portfolio-assistant
    HostName github.com
    User git
    IdentityFile ~/.ssh/portfolio-assistant
    IdentitiesOnly yes
EOF
chmod 600 ~/.ssh/config
# the public half: safe to copy and paste anywhere
cat ~/.ssh/portfolio-assistant.pub

You should see: a "randomart" picture, then one line starting with ssh-ed25519 AAAA and ending with zindivps portfolio-assistant. Select that whole line and copy it. Never copy the file without .pub: that's the private half, and it stays on the server.

4b. Give it to GitHub (browser).

  1. Open the repository's Settings → Deploy keys → Add deploy key.
  2. Title: zindivps · Key: paste the line · leave Allow write access unchecked → Add key. GitHub may ask for your password or 2FA code first.

4c. Clone on the server.

ssh -T git@github-portfolio-assistant

You should see (first time only) Are you sure you want to continue connecting (yes/no/[fingerprint])?. Check that the fingerprint above it is GitHub's, SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU, then type yes. Next: Hi amine-a11/portfolio-assistant! You've successfully authenticated, but GitHub does not provide shell access. That message is a success. Permission denied (publickey) means the key from 4b wasn't saved.

git clone git@github-portfolio-assistant:amine-a11/portfolio-assistant.git ~/apps/portfolio-assistant
cd ~/apps/portfolio-assistant
git log --oneline -1
ls

You should see: your latest commit (for example f0422fb first commit), then Dockerfile README.md app data deploy docker-compose.yml evals guide knowledge pyproject.toml scripts tests.

4d. Copy the keys file from your PC. .env is not in git, on purpose, so it travels on its own, encrypted by SSH:

scp C:\dev\portfolio-assistant\.env zindivps:~/apps/portfolio-assistant/.env

You should see: one progress line ending in 100%.

cd ~/apps/portfolio-assistant
# git must ignore it (prints ".env"), so a future commit on the server can't publish your keys
git check-ignore .env

You should see: .env.

Step 5 · Adjust the server's .env

Your local .env already has every provider key and the LLM_MODELS order. The server needs three more settings:

  • ONNX_THREADS=4: the VPS has 4 cores, and the default of 8 would make voice slower (chapter 7);
  • CORS_ORIGINS: only your site's pages may call the API from a browser (chapter 5);
  • ADMIN_TOKEN: a long random password for the reindex endpoint, generated on the spot.
cd ~/apps/portfolio-assistant
# Windows line endings would end up inside the values
sed -i 's/\r$//' .env
# remove old copies of these three lines, if any, then add them
sed -i '/^\(ONNX_THREADS\|CORS_ORIGINS\|ADMIN_TOKEN\)=/d' .env
echo >> .env
cat >> .env <<EOF
ONNX_THREADS=4
CORS_ORIGINS=https://aminehajji.dev,https://www.aminehajji.dev
ADMIN_TOKEN=$(openssl rand -hex 32)
EOF
# only your user can read the keys
chmod 600 .env
# show the setting names (not the values)
grep -o '^[A-Z_]*=' .env

You should see these 11 names, in any order: LLM_MODELS GEMINI_API_KEY LLM_REASONING_EFFORT QUERY_REWRITE OPENROUTER_API_KEY CLOUDFLARE_API_KEY CLOUDFLARE_ACCOUNT_ID GROQ_API_KEY ONNX_THREADS CORS_ORIGINS ADMIN_TOKEN.

Why the token never leaves the server

You never need to see ADMIN_TOKEN: later commands read it straight from the file with $(grep '^ADMIN_TOKEN=' .env | cut -d= -f2). A secret you never copy can't end up in a chat, a screenshot or another machine's shell history.

Step 6 · Build and start the container

cd ~/apps/portfolio-assistant
docker compose up -d --build

The first build takes about 5 to 10 minutes: it downloads Python, installs the libraries and bakes the speech models (~320 MB) into the image. Later builds reuse the cached layers and take seconds when only code changed (why). When it returns, watch the app start:

docker compose logs -f

You should see, within a minute:

  • knowledge: can't use https://aminehajji.dev/knowledge.json (…); using the bundled snapshot knowledge.json. This is expected for now: the live site doesn't publish that file until step 9, so the backend uses the copy built into the image.
  • index: 25 documents -> … chunks;
  • ready: llm=groq/qwen/qwen3.8-27b → gemini/… → … stt=faster-whisper tts=kokoro. Every model in LLM_MODELS should appear in that arrow list. A line like LLM … skipped: set GROQ_API_KEY in .env means a key is missing: fix .env, then run docker compose up -d.
  • voice: models ready.

Press Ctrl+C to stop watching (the container keeps running). Then ask it directly, without nginx:

curl -s localhost:8000/api/health; echo
docker compose ps

You should see: {"ok":true,"chunks":…} with a number above 0, and the assistant service with status Up. Because of restart: unless-stopped, Docker also restarts it after a crash or a server reboot.

Step 7 · nginx and HTTPS for api.aminehajji.dev

First check that step 2's DNS record works (nslookup api.aminehajji.dev on your PC). Then add the site to nginx (the file is explained below):

cd ~/apps/portfolio-assistant
sudo cp deploy/nginx-api.conf /etc/nginx/sites-available/api.aminehajji.dev
sudo ln -s /etc/nginx/sites-available/api.aminehajji.dev /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
curl -s http://api.aminehajji.dev/api/health; echo

You should see: syntax is ok and test is successful from nginx -t, then the same {"ok":true,…} as before, this time through nginx. If nginx -t reports an error, don't reload: read the line number it gives.

Now the free HTTPS certificate, the same way your other sites got theirs:

sudo certbot --nginx -d api.aminehajji.dev

You should see: Successfully deployed certificate for api.aminehajji.dev. If it asks questions (email, terms), answer as you did for your other domains. Certbot adds HTTPS to the nginx file, reloads nginx by itself, and renews the certificate automatically.

curl -s https://api.aminehajji.dev/api/health; echo
# HTTP/2 stays off on this server (no output = good)
sudo nginx -T 2>/dev/null | grep -n http2

You should see: {"ok":true,…} over HTTPS, and no output from the second command.

Step 8 · Check that streaming works through nginx

curl -N -X POST https://api.aminehajji.dev/api/chat \
  -H "Content-Type: application/json" -H "X-Client-Id: test-test-test-test" \
  -d '{"message":"What is EVMirror?"}'

You should see: an event: meta block, then many event: delta blocks appearing one after another as the answer is written, then event: done. If everything appears at once at the end, proxy_buffering off is missing from the nginx file.

This test conversation is saved like any other, which is fine.

Step 9 · Switch the ✦ button on in the live site

Your site is built on the server: the code is a git clone in ~/apps/my-portfolio, and nginx serves its dist/ folder. The assistant's frontend code is already pushed to GitHub (commit ebd973c). Telling the build where the API lives makes the button appear:

cd ~/apps/my-portfolio
git pull origin main
# the build reads this file; without it the button stays hidden
echo "VITE_ASSISTANT_URL=https://api.aminehajji.dev" > .env.production
npm run build

You should see: git pull listing the new src/assistant/… files, and the build's last line knowledge: 24 documents → dist/knowledge.json. No npm install is needed: no library was added.

# the address is baked into the site's code (prints one file name)
grep -l "api.aminehajji.dev" dist/assets/*.js
# the content file the assistant reads (prints the start of a JSON file, not HTML)
curl -s https://aminehajji.dev/knowledge.json | head -c 120; echo

You should see: one dist/assets/….js file name, then text starting with {. If the second command prints <!doctype html>, the build didn't write dist/knowledge.json.

Don't commit .env.production

This file exists only on the server. If you ever add a file with the same name to the repository, the next git pull here will refuse to overwrite it: delete the server's copy first.

Step 10 · Teach the assistant the live content

The container is still using the snapshot from step 6. Ask it to read the live site's content now:

cd ~/apps/portfolio-assistant
curl -s -X POST -H "Authorization: Bearer $(grep '^ADMIN_TOKEN=' .env | cut -d= -f2)" \
  http://127.0.0.1:8000/api/admin/reindex; echo

You should see: {"ok":true,"documents":25,"chunks":…}: the site's 24 documents plus knowledge/assistant.md. 401 means the token didn't match: check that .env has exactly one ADMIN_TOKEN= line, then run docker compose up -d.

Repeat this command after every site deploy (step 9), so the assistant learns what you changed.

Step 11 · Try it like a visitor

  1. Open aminehajji.dev and press Ctrl+F5 (reloads without the cache).
  2. The ✦ button is at the bottom right. Click it (or press Ctrl+K) and ask What is EVMirror?: the answer appears word by word, with numbered sources that link to your pages.
  3. Open a project page and use Summarize this page.
  4. Click the waveform button, allow the microphone, and ask a question out loud.
  5. Do the same on your phone, on mobile data (not your Wi-Fi), to test it as a stranger would.
  6. Watch your questions arrive: docker compose logs -f in ~/apps/portfolio-assistant shows answering with groq/… for each one.

That's it: it's live. 🎉

If something goes wrong

What you seeWhat it means, and the fix
permission denied while trying to connect to the Docker daemon socketYou haven't logged in again since step 3: exit, then ssh zindivps.
certbot: DNS problem: NXDOMAINThe DNS record from step 2 isn't visible yet. Wait, check with nslookup api.aminehajji.dev, then run certbot again.
Logs: sqlite3.OperationalError: unable to open database file, status RestartingThe database volume is owned by root, and the app runs as the user assistant. The Dockerfile now creates data/db with the right owner; a volume made by an older image keeps the wrong one. Before any real conversations exist: docker compose down -v (deletes the volume), then docker compose up -d --build.
502 Bad Gateway on api.aminehajji.devnginx works but the container doesn't answer: docker compose ps and docker compose logs --tail 50.
No ✦ button on the live siteBrowser cache (Ctrl+F5), or the build didn't see .env.production: re-run step 9 and its grep check.
Browser console: blocked by CORS policyThe page's address isn't in CORS_ORIGINS. Fix .env, then docker compose up -d --force-recreate.
The widget says the free usage limit is reachedEvery model in LLM_MODELS answered 429. The logs show which ones (LLM error 429). It recovers by itself within a minute, or at the next daily reset.
Voice questions fail with 413client_max_body_size 6m is missing from the nginx file (see the quiz at the end).
The build is killed, or the server is very slowMemory: check with free -h. The container needs about 1.4 GB; text-only mode needs much less (below).

The Docker image

A Docker image is a snapshot of everything needed to run the app (Python, dependencies, code, models), built from a recipe. The same image runs identically on your laptop and the server.

  • Dependencies before code. Docker caches each step (layer) and reuses it until its inputs change. Installing from pyproject.toml before copying app/ means editing code doesn't reinstall every library.
  • Models baked in (~320 MB) so the container starts without downloading anything. The trade-off is a bigger image; mounting a models/ volume is the alternative.
  • Only named folders are copied (COPY app, COPY knowledge…), never the whole directory, so .env can't end up inside the image. The keys reach the container when it starts, through env_file.
  • Non-root user. If the app were ever compromised, it couldn't modify the system.

The SQLite file lives in a named volume, so conversations survive rebuilds. The port is published on 127.0.0.1 only: the outside world can't reach the container directly, which is also what makes trusting X-Forwarded-For safe (chapter 5).

nginx as a reverse proxy

proxy_buffering off is the line that makes streaming work (chapter 5's quiz). client_max_body_size 6m lets voice recordings through: nginx's default of 1 MB would reject longer questions with a 413.

Will my server cope?

ConfigurationRAM (approx.)CPU
Text chat only (STT_PROVIDER=none, TTS_PROVIDER=none)~300 MBNegligible: embedding one query is milliseconds
Full voice (Whisper base.en + Kokoro)~1 to 1.5 GBKokoro needs ~2+ real cores to keep up with playback

Measured before deploying, with the container limited to 4 cores like the VPS: about 1.4 GB of RAM, a first word in about 4 s, and about 3 s each for speech-to-text and text-to-speech on a short sentence. The VPS had 5.1 GB free. If the server ever struggles, there's a ladder of options, all config-only:

  1. TTS_PROVIDER=none: the widget falls back to the browser's built-in voice (free, instant, less natural; the orb animation is simulated).
  2. STT_PROVIDER=openai with Groq's hosted Whisper (STT_BASE_URL=https://api.groq.com/openai/v1, STT_MODEL=whisper-large-v3-turbo): faster and more accurate than base.en, free tier.
  3. Keep everything local but use a smaller Whisper (tiny.en), at some cost in accuracy.

Operating it

Free-tier reality

Free tiers have per-minute and per-day request limits, and capacity varies by hour. In practice: the per-IP limits (10/min, 150/day) keep one visitor from exhausting the quota; LiteLLM's router moves a question to the next model in LLM_MODELS on any 429/503 (chapter 1), so the free quotas of four companies add up (about 2,000 questions a day); and the widget shows a friendly "try again in a minute" only when all of them fail. If that ever isn't enough, add another free provider's key and model to .env.

Watching it

All of these run on the server, inside ~/apps/portfolio-assistant:

# requests, "answering with …", fallbacks, errors (Ctrl+C to stop)
docker compose logs -f --since 1h
# the last 20 questions visitors asked
docker compose exec assistant python -c "import sqlite3; db = sqlite3.connect('/app/data/db/assistant.db'); [print(r[0]) for r in db.execute(\"SELECT content FROM messages WHERE role='user' ORDER BY id DESC LIMIT 20\")]"

Read what visitors ask: it's market research for your portfolio, and every failed question is a candidate for evals/questions.jsonl. The 👍/👎 ratings are at GET /api/admin/feedback (same Authorization header as reindex).

Updating

  • New content (you edited src/content/): push the site, run step 9's git pull and npm run build, then step 10's reindex. No backend change.
  • Different model order or a new key: edit .env on the server (nano .env), then docker compose up -d: it restarts with the new config.
  • New backend code: run pytest on your PC and push, then on the server: cd ~/apps/portfolio-assistant && git pull && docker compose up -d --build. The server's .env isn't touched by git pull.
  • Backups: the only state is the SQLite file in the volume. Copy it now and then with docker compose cp assistant:/app/data/db/assistant.db ./backup.db.

Security checklist

  • ☐ The provider keys are only in the server's .env (chmod 600), never in git or the image.
  • ☐ The server's GitHub deploy key is read-only and opens only this repository.
  • ☐ CORS_ORIGINS lists only your site's origins.
  • ☐ ADMIN_TOKEN is long and random (reindex is disabled when it's empty).
  • ☐ The container port is bound to 127.0.0.1 and HTTPS is on (certbot).
  • ☐ Rate limits are on (defaults), and input sizes are capped: 1,500-character messages, 5 MB audio, 600-character TTS.
  • ☐ The site mentions that chats are stored, and you've decided how long to keep them.
  • ☐ If a key ever leaks: delete it on that provider's keys page (the links are in .env.example), create a new one, put it in the server's .env, then docker compose up -d.

Voice questions longer than a few seconds fail in production with HTTP 413, but work locally. Why?

Proxies have their own limits and timeouts. When something works locally and fails behind a proxy, check the proxy first.

Right after step 6, the logs say the backend can't use aminehajji.dev/knowledge.json. What happens to visitors?

The live site answered that URL with its HTML page, which isn't valid JSON. Instead of failing to start, the backend falls back to data/knowledge.json, copied into the image at build time.

Go further