docs: add DEPLOY.md — VPS deploy guide (Docker + nginx + Certbot)

Production deploy playbook for Osteo Report. Single nginx:alpine
container behind a host reverse proxy; no backend, no database, no
server-side state. Praticien data lives in the browser and in the
exported PDFs themselves.

Sections cover:
- Topology + container/host port table.
- Required environment (.env): APP_SITE_NAME / BRAND_NAME /
  FOOTER_NAME / TAGLINE + optional PORT. No secrets.
- VPS provisioning (Ubuntu 24.04 LTS, 1 vCPU / 1-2 GB RAM, DNS,
  baseline apt packages).
- Firewall — cloud provider security group + UFW on the VM, with
  explicit "do NOT expose 8080" note.
- Docker install + tuned daemon.json (json-file log driver capped
  10MB × 5, live-restore).
- First-time setup, routine deploys via `git fetch + reset --hard
  origin/master + docker compose up --build -d`.
- Data persistence + backups: just the .env file (no volumes).
  Daily cron + retention + off-VPS sync.
- TLS reverse proxy — Option A (host nginx + Certbot with security
  headers HSTS/XFO/XCTO/Referrer-Policy/Permissions-Policy/CSP),
  Option B (Caddy auto-TLS Caddyfile).
- Sanity checks — TLS redirect, env.js cache headers, no-public-8080
  verification via nc + nmap.
- Hardening — non-root deploy user, disable root + password SSH,
  optional SSH port move, unattended security upgrades, fail2ban,
  external lockdown nmap.
- Rollback (git reset + rebuild — no data to restore).
- Health checks table, troubleshooting (9 common failures with
  recipes), operational notes (log destinations, manual prune,
  provider-specific RAM hints).

README.md DEPLOY.md link now points at a real document.
This commit is contained in:
Bastien Chanot committed 2026-05-21 04:13:28 +02:00
1 parent 8385b49bbe
commit 98117b3b7f
1 file changed
+625
+625
View File
@@ -0,0 +1,625 @@
# Deploy
Single nginx:alpine container behind a host reverse proxy that terminates
TLS. The container serves a static SPA bundle from `/usr/share/nginx/html`
and a runtime-injected `env.js`; there is no backend, no database, no
persistent server-side state. Praticien data lives in the browser
(`sessionStorage` / `localStorage`) and in the exported PDFs themselves
(JSON attached natively to each PDF).
---
## What gets deployed
| Service | Image source | Port (container) | Port (host) | Role |
| ------- | ----------------------------------------- | ---------------- | --------------- | ----------------------------------------------------------------------------------- |
| `app` | local build (multi-stage `Dockerfile`) | `${PORT:-8080}` | `${PORT:-8080}` | Serves the SPA (`dist/`) + runtime `env.js`. nginx:alpine inside, SPA fallback to `index.html`. |
The host should publish only ports `22`, `80`, `443` to the internet. The
container port (`8080` by default) should stay loopback-only — the host
reverse proxy reads from it on `127.0.0.1:8080`.
---
## Required environment
All vars live in a single `.env` file at the project root on the VPS
(read by `docker compose` via `env_file: .env`). Defaults sit in
`docker/entrypoint.sh` and `src/config/env.ts`; production should set
each one explicitly.
| Variable | Required | Default | Notes |
| ----------------- | -------- | ---------------- | ------------------------------------------------------------------------------------ |
| `APP_SITE_NAME` | yes | `Osteo Report` | Browser `<title>`, OG `site_name`. |
| `APP_BRAND_NAME` | yes | `Osteo Report` | Header brand block, PDF header. Praticien-visible identity. |
| `APP_FOOTER_NAME` | yes | `Osteo Report` | Footer copyright line. |
| `APP_TAGLINE` | yes | `Bilans d'ostéopathie animalière` | Hero tagline on Home. |
| `PORT` | no | `8080` | Container listen port. Override to relocate the loopback bind. |
No secrets are required — there is no API, no DB, no provider credential.
The `.env` file is not sensitive but should still be `chmod 600` to keep
local identity overrides private.
---
## Provision the VPS
| Resource | Recommended minimum |
| ------------ | ----------------------------------------------- |
| CPU | 1 vCPU |
| RAM | 1 GB (build runs out-of-band — see below) |
| Disk | 10 GB |
| OS | Ubuntu 24.04 LTS (or any recent Debian-family) |
Build-time RAM peaks around 1 GB (Vite + TS + Tailwind). If your VPS only
has 1 GB, either swap-enable the host or build the image locally and push
it to a registry — the runtime image is well under 100 MB.
DNS:
```text
# A record on your domain registrar / DNS provider
osteo.example.com → <vps-ipv4>
osteo.example.com (AAAA) → <vps-ipv6> # optional
```
SSH key copied to the VPS before disabling password auth (see Hardening
below).
Baseline packages (apt):
```bash
apt-get update
apt-get install -y git curl ufw fail2ban ca-certificates gnupg \
nginx certbot python3-certbot-nginx unattended-upgrades
```
---
## Firewall (two layers)
### Layer 1 — cloud provider security group
| Source | Port | Protocol | Rule |
| ---------------------- | ------- | -------- | ------- |
| your office / home IP | 22 | TCP | allow |
| 0.0.0.0/0 | 80 | TCP | allow |
| 0.0.0.0/0 | 443 | TCP | allow |
| any | other | any | deny |
Cheat sheet:
- **Scaleway**: Console → Security Groups → create + bind to instance.
- **Hetzner**: Console → Firewalls → attach to server.
- **OVH**: Public Cloud → Networking → Security groups (legacy: iptables).
- **DigitalOcean**: Networking → Firewalls.
### Layer 2 — UFW on the VM
```bash
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp # SSH
ufw allow 80/tcp # HTTP (for ACME challenge + redirect)
ufw allow 443/tcp # HTTPS
ufw --force enable
ufw status verbose
```
Do **not** open `8080` (or whatever `PORT` you pick). The host nginx talks
to the container on `127.0.0.1:8080`.
---
## Install Docker (production-tuned)
```bash
curl -fsSL https://get.docker.com | sh
systemctl enable --now docker
# Cap container log volume — JSON-file driver with rotation
cat > /etc/docker/daemon.json <<'EOF'
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "5"
},
"live-restore": true
}
EOF
systemctl restart docker
```
Confirm:
```bash
docker version
docker info | grep -i 'logging driver\|live restore'
```
---
## First-time VPS setup
```bash
# As your non-root deploy user (see Hardening §1 if you have not made one yet)
cd ~
git clone https://git.bchanot.fr/bchanot/osteo-report.git
cd osteo-report
# Configure identity
cp .env.example .env
$EDITOR .env # set APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE, etc.
# First build (publishes to 127.0.0.1:8080)
docker compose up --build -d
docker compose ps
docker compose logs --tail=50
# Loopback sanity check
curl -sI http://127.0.0.1:8080/ | head -1 # expect 200 OK
curl -s http://127.0.0.1:8080/env.js # expect window.__APP_CONFIG__ = {...};
```
If the build OOMs on a 1 GB VPS, build locally and rsync the resulting
`dist/` over, then bind-mount it into a plain `nginx:alpine` until you
upsize.
---
## Routine deploys
This project has no `scripts/deploy.sh` yet. Pull-and-recompose from the
VPS is the path:
```bash
cd ~/osteo-report
git fetch origin
git reset --hard origin/master # default branch is "master" on this remote
docker compose up --build -d
docker image prune -f # reclaim old build layers
```
Verify post-deploy:
```bash
docker compose ps
curl -sI https://osteo.example.com/ | head -3
```
For zero-downtime updates, `docker compose up --build -d` rebuilds the
image then recreates the container; the container restart is sub-second
because nginx:alpine boots instantly. There is no warmup phase.
---
## Data persistence
There are no server-side volumes to back up:
- **In-flight session data** lives in the praticien's browser
(`sessionStorage osteo:draft`, `localStorage osteo:lastPractitioner`,
`localStorage osteo:locale`, `sessionStorage osteo:disclaimer-shown`).
- **Long-term record** is the exported PDF — the full report JSON is
attached natively (`AFRelationship.Data`). Re-importing the PDF
restores the session.
The only "data" the server holds is the SPA bundle and `env.js`, both
regenerated on every build.
---
## Backups (cron + retention)
Because there is no server-side state, the backup target is the source
repository plus the `.env` file.
### .env snapshot
```bash
# /opt/backup-osteo.sh
#!/bin/sh
set -e
DEST="/var/backups/osteo"
DATE="$(date -u +%Y%m%d)"
mkdir -p "$DEST"
cp /home/<deploy-user>/osteo-report/.env "$DEST/env-$DATE"
chmod 600 "$DEST/env-$DATE"
find "$DEST" -name 'env-*' -mtime +30 -delete
```
Make executable:
```bash
chmod 700 /opt/backup-osteo.sh
chown root:root /opt/backup-osteo.sh
```
### Cron
```bash
# crontab -e (root)
5 3 * * * /opt/backup-osteo.sh >> /var/log/backup-osteo.log 2>&1
```
### Off-VPS storage (optional but recommended)
Sync the backup directory to S3-compatible storage (Scaleway Object
Storage, B2, etc.):
```bash
# After installing rclone or aws-cli
aws s3 sync /var/backups/osteo s3://<bucket>/osteo/ --storage-class STANDARD_IA
```
### Restore
```bash
docker compose down
cp /var/backups/osteo/env-<date> /home/<deploy-user>/osteo-report/.env
docker compose up --build -d
curl -sI https://osteo.example.com/
```
The praticien's exported PDFs are the real long-term store. If the VPS
disappeared entirely, a fresh `git clone` + `.env` + `docker compose up`
on a new host reproduces the live app.
---
## Behind a domain + TLS reverse proxy
### Option A — host nginx + Certbot
DNS A/AAAA records pointing at the VPS, UFW allowing 80/443, then on the
VPS:
```bash
# /etc/nginx/sites-available/osteo
server {
listen 80;
listen [::]:80;
server_name osteo.example.com;
# Certbot will rewrite this block to add the 301 redirect.
location /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
}
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name osteo.example.com;
# ssl_certificate + ssl_certificate_key written by certbot
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Enable + obtain certificate:
```bash
ln -s /etc/nginx/sites-available/osteo /etc/nginx/sites-enabled/osteo
nginx -t && systemctl reload nginx
certbot --nginx -d osteo.example.com
systemctl status certbot.timer # auto-renew preinstalled on Ubuntu
```
#### Security headers (Option A only)
Add inside the `listen 443` block (under any existing `location` rules
the certbot template inserted):
```nginx
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" always;
```
Reload + verify:
```bash
nginx -t && systemctl reload nginx
curl -sI https://osteo.example.com/ | grep -iE 'strict-transport|x-frame|content-security'
# Cross-check externally:
# https://securityheaders.com/?q=osteo.example.com
# https://www.ssllabs.com/ssltest/analyze.html?d=osteo.example.com
```
The `'unsafe-inline'` on `style-src` is needed because Tailwind injects
inline `<style>` tags via the runtime engine; tighten if a Tailwind
build-time export gets adopted later. `img-src` includes `data:` and
`blob:` because the canvas rasterization pipeline produces blob URLs and
the PDF preview emits data URLs.
### Option B — Caddy (auto-TLS, single file)
```bash
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf https://dl.cloudsmith.io/public/caddy/stable/gpg.key | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/caddy-stable-archive-keyring.gpg] https://dl.cloudsmith.io/public/caddy/stable/deb/debian any-version main" \
> /etc/apt/sources.list.d/caddy-stable.list
apt-get update && apt-get install -y caddy
cat > /etc/caddy/Caddyfile <<'EOF'
osteo.example.com {
encode gzip zstd
reverse_proxy 127.0.0.1:8080
header {
Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
Permissions-Policy "camera=(), microphone=(), geolocation=()"
Content-Security-Policy "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
}
}
EOF
systemctl reload caddy
```
Caddy handles TLS issuance + renewal automatically.
### Backend CORS
N/A. The app has no backend and makes no cross-origin requests. The only
runtime fetches target the same origin (SVG assets, `env.js`).
### Frontend API base URL
N/A. There is no build-time API URL var; the app is static.
### Sanity checks
```bash
# HTTPS redirect on port 80
curl -sI http://osteo.example.com/ | grep -i location # expect Location: https://...
# TLS itself
curl -sI https://osteo.example.com/ | head -3 # expect HTTP/2 200
# env.js shipped fresh (no caching)
curl -sI https://osteo.example.com/env.js | grep -i cache-control
# expect: Cache-Control: no-store, no-cache, must-revalidate
# Internal port is NOT publicly bound
nc -zv <vps-public-ip> 8080 2>&1 | grep -i refused # expect "Connection refused"
```
---
## Post-deploy hardening
### 1. Non-root deploy user
```bash
adduser deploy
usermod -aG docker deploy
mkdir -p /home/deploy/.ssh
cp ~/.ssh/authorized_keys /home/deploy/.ssh/
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keys
echo 'deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl, /usr/bin/journalctl' \
> /etc/sudoers.d/deploy
```
### 2. Disable root + password SSH
In `/etc/ssh/sshd_config`:
```text
PermitRootLogin prohibit-password
PasswordAuthentication no
PubkeyAuthentication yes
```
Reload + verify on a second terminal *before* closing the first one:
```bash
systemctl reload ssh
ssh deploy@osteo.example.com 'echo ok'
```
### 3. (Optional) Move SSH off port 22
Open the new port everywhere before closing 22:
```bash
ufw allow 2222/tcp # 1. UFW
# 2. Add 2222 to cloud security group
# 3. /etc/ssh/sshd_config: Port 2222 (keep Port 22 temporarily)
systemctl reload ssh
ssh -p 2222 deploy@osteo.example.com 'echo ok' # confirm
# 4. Remove Port 22 from sshd_config + UFW + cloud SG
```
### 4. Unattended security upgrades
```bash
apt-get install -y unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades
```
Confirm `/etc/apt/apt.conf.d/20auto-upgrades` enables `Update-Package-Lists`
and `Unattended-Upgrade`.
### 5. fail2ban
```bash
systemctl enable --now fail2ban
fail2ban-client status sshd
```
### 6. Final lockdown check
```bash
# From OUTSIDE the VPS
nmap -Pn -p 22,80,443,8080,2222 <vps-public-ip>
# 22: filtered (if SSH moved) or open (if not)
# 80: open
# 443: open
# 8080: filtered ← MUST NOT be open
# 2222: open ← if SSH was moved
# Password-SSH attempt — should fail
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no deploy@osteo.example.com
# Expect: Permission denied (publickey).
```
---
## Rollback
```bash
cd ~/osteo-report
git reflog | head -20 # find the known-good SHA
git reset --hard <known-good-sha>
docker compose up --build -d
curl -sI https://osteo.example.com/ | head -1
```
Because there is no server-side state to corrupt, rollback is purely a
code revert + rebuild. Praticien browsers retain their own data; PDFs
already exported are unaffected.
---
## Health checks
| URL | Expected |
| --------------------------------------- | ----------------------------------------- |
| `https://osteo.example.com/` | HTTP/2 200, HTML containing `<div id="root">` |
| `https://osteo.example.com/env.js` | HTTP/2 200, `Cache-Control: no-store, no-cache, must-revalidate`, body starts with `window.__APP_CONFIG__ = {` |
| `https://osteo.example.com/assets/<hash>.js` | HTTP/2 200, `Cache-Control: public, max-age=31536000, immutable` |
| `https://osteo.example.com/nonexistent` | HTTP/2 200 (SPA fallback serves `index.html`) |
| `http://127.0.0.1:8080/` (on VPS) | HTTP/1.1 200 |
There is no `/health` endpoint — the container only serves static assets.
Liveness is "nginx process up + serving 200 on `/`".
---
## Troubleshooting
### container won't start
```bash
docker compose logs --tail=200 app
```
Common: `.env` missing or unreadable (compose will still start but
`APP_*` defaults apply); permission error on `/entrypoint.sh` (rebuild
with `--no-cache`).
### 5xx from the site
The container itself only serves static files — a 5xx almost always
comes from the host reverse proxy.
```bash
journalctl -u nginx --since "10 min ago" # Option A
journalctl -u caddy --since "10 min ago" # Option B
```
Most common: `proxy_pass` target wrong (`127.0.0.1:8080` vs container
port) or container down.
### CORS rejected in browser
The app makes no cross-origin requests. If you see a CORS error, the
likely cause is a misconfigured CSP — check the `Content-Security-Policy`
header against the failing resource URL.
### 502 bad gateway from host nginx
The container is down or listening on a different port. Verify:
```bash
docker compose ps
ss -ltnp | grep 8080 # container should own the port
curl -sI http://127.0.0.1:8080/ | head -1
```
### SSL renewal failed
```bash
systemctl status certbot.timer
certbot renew --dry-run
journalctl -u certbot --since "1 week ago"
```
Common: UFW dropping port 80 (ACME HTTP-01 challenge fails) or the host
nginx site config moved without reloading.
### volume / data unexpectedly empty
N/A — this app has no volumes.
### disk full
```bash
df -h
docker system df
docker system prune -a -f # purge unused images/layers
journalctl --disk-usage
journalctl --vacuum-time=7d
```
The Docker log driver is capped at `5×10MB` per container in this setup
(see `/etc/docker/daemon.json`); runaway logs should not happen.
### restart loop
```bash
docker compose ps # status column
docker compose logs --tail=200 app
```
Most common: `entrypoint.sh` non-executable (`chmod +x` line missing from
Dockerfile after a copy edit) or nginx config syntax error (test with
`docker compose run --rm app nginx -t`).
### container log explosion
Already mitigated by `json-file` driver caps. If you see disk pressure
from `/var/lib/docker/containers/<id>/*.log` anyway, lower the cap in
`/etc/docker/daemon.json` and restart Docker.
---
## Operational notes
- **Logs**: Docker JSON-file driver, capped at `5 × 10MB` per container
(`/etc/docker/daemon.json`). Host nginx logs in `/var/log/nginx/`;
rotate via logrotate (default Ubuntu config). Certbot logs in
`/var/log/letsencrypt/`.
- **Manual log prune**: `docker compose logs --no-color > /tmp/x; truncate -s 0 $(docker inspect --format='{{.LogPath}}' osteo-report-app-1)`.
- **Key rotation**: `.env` carries no secret material, but if
`APP_BRAND_NAME` etc. need to change, edit `.env` + `docker compose up
-d` (no rebuild — `entrypoint.sh` reads env on container start).
- **Provider-specific**:
- Scaleway DEV1-S works; DEV1-XS hits build OOM.
- Hetzner CX22 is the cheapest reliable choice for the build itself.
- On any 1 GB VPS, build locally and skip in-place compose builds.