Files
news-platform/docs/deployment.md
T
Artur Moreira b629f6c6aa feat(frontend): PT shell i18n, html lang pt-PT, i18n docs (BIT-739)
- Set document language to full BCP-47 from domain config (e.g. pt-PT).
- Extend ui-i18n with service errors, ad labels, ARIA landmarks, category
  meta fallback, and localized search upstream message.
- Localize ArticleHeader (dates, reading time, breadcrumb); omit duplicate
  breadcrumb when institutional chrome already provides one.

Docs: add docs/i18n.md strategy sketch; domains.md and deployment.md
(BRIDGE_INTERNAL_URL) cross-links.

Paperclip-Agent: ac1be104-8818-496a-80c5-fbc590a87855
Paperclip-Issue: 182b154e-5ad4-4965-9f30-50a66ef51ce0
Paperclip-Run: 6ce7746f-bfb6-4486-a1f5-aed26fe8e149
Made-with: Cursor
2026-04-02 20:06:48 +00:00

191 lines
11 KiB
Markdown

# Deployment — LXC on Proxmox
> **NPM (manual, board):** Configure [Nginx Proxy Manager](https://nginxproxymanager.com/) with hostname **`newsproject.bitreport.pt`** pointing to `http://<CT-ip>:80`, TLS enabled. Termination stays at NPM; the CT Nginx listens on port 80 only.
---
## Overview
The platform runs on a single LXC container on Proxmox for the initial test deployment. The container hosts all services: Nginx reverse proxy, Astro frontend (Node.js), Fastify bridge (Node.js), WordPress (Docker), MariaDB (Docker), and Redis.
**Bootstrap order:** create the CT → run **`deploy/lxc/setup.sh`** on the CT → clone or sync repo to `/opt/news-platform` → run **`deploy/scripts/deploy.sh`** → configure NPM as above → run **`deploy/scripts/smoke-newsproject.sh`** with `BASE_URL=https://newsproject.bitreport.pt`.
---
## LXC Container Spec
| Property | Value |
|----------|-------|
| Name | `news-project-test` |
| OS | Ubuntu 24.04 LTS |
| CPU | 2 cores |
| RAM | 4 GB |
| Disk | 20 GB |
| Network | Bridge (vmbr0), DHCP or static IP |
| Domain | `newsproject.bitreport.pt` |
---
## Service Layout
```
LXC: news-project-test
│
├── nginx (host) :80, :443
│ └── reverse proxy → :4321 (Astro)
│
├── astro-frontend (PM2 / systemd) :4321
│ └── node dist/server/entry.mjs
│
├── fastify-bridge (PM2 / systemd) :3200
│ └── node dist/server.js
│
├── redis (host or Docker) :6379
│
└── Docker Compose
├── nginx (compose) :8080 → wordpress PHP-FPM
└── mariadb (db) :3306 (internal only)
```
---
## Setup Script (`deploy/lxc/setup.sh`)
Versioned script on the repo (run as **root** on a fresh Ubuntu 24.04 CT):
```bash
sudo bash /opt/news-platform/deploy/lxc/setup.sh
```
It installs nginx, Redis, Docker (+ compose plugin), Node.js 22, and PM2, and enables `docker` and `redis-server`.
---
## Nginx Config (`deploy/nginx/newsproject.bitreport.pt.conf` + `conf.d/`)
The canonical site config is **`deploy/nginx/newsproject.bitreport.pt.conf`** (install via `deploy/scripts/deploy.sh`). It listens as **`default_server`** on port 80 with **`server_name _`**, so **any hostname** NPM forwards to this CT hits the news stack (no per-domain `server_name` on the CT). Add **`config/domains/<hostname>.json`** + a **proxy host in NPM**; redeploy/restart bridge if needed.
**`deploy/nginx/conf.d/99-news-platform-wp-map.conf`** maps `Host` → WordPress upstream port (`8080` default; `andebol.net` → `8081`). If you add another domain with its own Docker WordPress port, extend that `map` and reload Nginx.
`deploy/scripts/deploy.sh` removes **`/etc/nginx/sites-enabled/default`** so the default Debian welcome page does not steal unmatched hosts.
Minimal shape (reference only — use the checked-in file, not this excerpt):
```nginx
server {
listen 80;
server_name newsproject.bitreport.pt;
location / {
proxy_pass http://127.0.0.1:4321;
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;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
```
HTTPS/TLS is terminated at Nginx Proxy Manager (NPM), which the board configures manually.
The checked-in `deploy/nginx/newsproject.bitreport.pt.conf` proxies WordPress on `127.0.0.1:$news_wp_port` (see `conf.d/99-news-platform-wp-map.conf`). **`wp-login.php`**, **`/wp-includes/`**, **`/wp-admin/css/`**, **`/wp-admin/js/`**, **`/wp-admin/images/`**, and **`/wp-content/languages/`** are **public** (no `allow`/`deny`), so browsers can load the login UI and register when `real_ip` exposes the true client IP. **`/wp-admin/`** (remainder), **`/wp-content/`** (other than `languages/`), and **`/wp-json/`** still use **`allow`** for loopback and RFC1918 **`$remote_addr`**. O bloco `server` define `X-Forwarded-Proto` a partir de `$http_x_forwarded_proto` (NPM) com *fallback* para `$scheme`, para o WordPress não assumir HTTP plano quando o browser usa HTTPS.
**Membership / registo:** in WordPress **Settings → General**, enable **Anyone can register** if the site should offer self-service signup (`/wp-login.php?action=register`, linked from the frontend as **`/registar`** when `auth_links` is true in `config/domains/<hostname>.json`).
**`wp-admin` and “public” reachability:** with **Nginx Proxy Manager** (or any reverse proxy on a private IP) in front of this CT, browsers worldwide connect to the public hostname, but the TCP client at the CT is the **proxy**. That address is usually inside `10.0.0.0/8` (or similar), so it matches `allow` — meaning **`https://…/wp-admin/` is reachable from the public Internet** through that chain, even though the config reads “RFC1918 only”. This matches operational reality; it is not a substitute for VPN-only admin unless you add controls at NPM/Cloudflare or enable **`ngx_http_realip_module`**: `set_real_ip_from` limited to **trusted** proxy IPs, `real_ip_header X-Forwarded-For`, then `allow`/`deny` apply to the restored client IP (test carefully; misconfiguration allows IP spoofing).
**WordPress 500 + «database connection»:** se o HTML do erro citar `db:3306`, tratar como stack Docker no CT (serviço `db`, `.env`, volumes) — ver `wordpress/README.md` § *Error establishing a database connection*.
---
## WordPress (Docker Compose)
A stack real está versionada em **`wordpress/docker-compose.yml`** (não duplicar aqui — evita deriva face à produção).
| Item | Valor actual |
|------|----------------|
| Database | **MariaDB 11** (`mariadb:11`), serviço `db`, porta 3306 só na rede Compose |
| WordPress | `wordpress:6-php8.3-fpm` + `nginx:alpine` sidecar per site; `WORDPRESS_DB_HOST: db:3306` (andebol: `db-andebol`) |
| URL pública | Preferir `WORDPRESS_PUBLIC_URL=https://newsproject.bitreport.pt` no `wordpress/.env`. Se faltar, o `wp-config` infere `https://` + `Host` quando o pedido chega **via Nginx do CT** e traz qualquer *hint* de proxy (`X-Forwarded-Proto`, `X-Forwarded-For`, ou `X-Real-IP`); `X-Forwarded-Proto` deve reflectir o HTTPS do NPM — ver `deploy/nginx/newsproject.bitreport.pt.conf`. |
| Arranque | `depends_on: db` com `condition: service_healthy` |
| Volumes | `db_data` (MySQL), `wp_content` (uploads/plugins) |
| Healthchecks | `db` / `db-andebol`: script oficial `--innodb_initialized`; FPM: socket TCP :9000; `nginx` / `nginx-andebol`: `wget` ao REST `/wp-json/wp/v2/` |
Operação e recuperação de **«Error establishing a database connection»**: `wordpress/README.md` (secção homónima). No CT, após `cd /opt/news-platform/wordpress`: `bash scripts/verify-db-connection.sh` confirma em cadeia `ps` + healthcheck do MariaDB + ligação desde o contentor `wordpress`.
**Automação LXC (`APP_DIR=/opt/news-platform` apenas):** `deploy/scripts/wordpress-ensure-public-url.sh` corrige `WORDPRESS_PUBLIC_URL` no `wordpress/.env` para `https://newsproject.bitreport.pt` quando ainda está vazio ou em `http://localhost:8080`. `deploy/scripts/wordpress-sync-options-url.sh` actualiza `siteurl`/`home` na tabela `wp_*options` para o mesmo URL (resolve redirects para `localhost` mesmo após instalação antiga). São invocados por `deploy/scripts/deploy.sh` e `deploy/scripts/webhook-deploy.sh`; o primeiro devolve código de saída `2` quando alterou o `.env` para o *caller* fazer `docker compose up -d --force-recreate wordpress nginx`.
---
## Service Start (PM2)
**Bridge URL on the CT:** Domain JSON often lists `bridge_endpoint` as loopback for dev. In production, set **`BRIDGE_INTERNAL_URL`** in the environment for the Astro process (e.g. in the PM2 ecosystem file or systemd unit) so SSR calls the real bridge (e.g. `http://127.0.0.1:3200` on the same host). The frontend merges this over the JSON value in `getDomainConfig()` — see `frontend/src/lib/domain.ts` and `frontend/.env.example`.
```bash
# Frontend
cd /opt/news-platform/frontend
pm2 start dist/server/entry.mjs --name astro-frontend -- --port 4321
# Bridge
cd /opt/news-platform/bridge
pm2 start dist/server.js --name fastify-bridge -- --port 3200
pm2 save
pm2 startup
```
---
## Deployment Checklist
- [ ] LXC container created and running
- [ ] Base packages installed (Node 22, nginx, redis, docker)
- [ ] Git repo cloned to `/opt/news-platform/`
- [ ] `config/domains/newsproject.bitreport.pt.json` populated
- [ ] Bridge dependencies installed and built
- [ ] Frontend dependencies installed and built
- [ ] WordPress Docker stack running (`docker compose up -d`)
- [ ] `WORDPRESS_PUBLIC_URL=https://newsproject.bitreport.pt` em `wordpress/.env` (alinhado com NPM / browser)
- [ ] WordPress configured (admin user, permalink structure `/%category%/%postname%/`)
- [ ] Bridge invalidator plugin activated in WP
- [ ] PM2 processes started and saved
- [ ] Nginx config symlinked and nginx reloaded
- [ ] DNS points `newsproject.bitreport.pt` to container IP
- [ ] NPM configured for HTTPS (board): hostname **`newsproject.bitreport.pt`** → CT port 80
- [ ] Smoke: `BASE_URL=https://newsproject.bitreport.pt bash deploy/scripts/smoke-newsproject.sh` (or `BASE_URL=http://127.0.0.1` on the CT)
- [ ] Sitemap accessible at `/sitemap.xml`
---
## Automatic deploy (Gitea → LXC)
After the first manual bootstrap, pushes to `main` can trigger a pull + selective rebuild on the container.
1. **Script** — `deploy/scripts/webhook-deploy.sh` compares `HEAD` to `origin/main`, runs `git reset --hard`, rebuilds bridge/frontend when those trees change, reloads nginx when `deploy/nginx/` changes, restarts bridge + frontend when `config/` changes (domain JSON is cached in the bridge process), and runs `docker compose` when `wordpress/` changes.
2. **Hook server** — `deploy/scripts/deploy-hook-server.mjs` listens on loopback (default `127.0.0.1:9090`), path `POST /hook`, and accepts `Authorization: Bearer <token>` or `X-Deploy-Token` matching `DEPLOY_HOOK_TOKEN`. It returns `202` and runs the script in the background. Systemd unit: `deploy/systemd/news-deploy-hook.service`; env template: `deploy/systemd/deploy-hook.env.example` → `/etc/news-platform/deploy-hook.env`.
3. **Gitea** — In the repo, add a **Webhook** on push to `main`, URL `http://<CT-ip-or-dns>:9090/hook` (only if Gitea can reach that host/port; otherwise use a self-hosted runner or SSH task that curls the hook from inside the VPN). Set a custom header or Bearer token to the same value as `DEPLOY_HOOK_TOKEN`. **Do not** expose the hook to the public internet without token and firewall allowlisting.
4. **Alternative** — Gitea **Actions** can `curl -fsS -X POST -H "Authorization: Bearer $TOKEN" http://.../hook` from a runner that has network access to the CT.
---
## Future: Multi-Container
When the platform scales beyond a single test container, each service moves to its own LXC or VM:
| Service | Container |
|---------|-----------|
| Astro frontend | `news-frontend-01`, `news-frontend-02` |
| Fastify bridge | `news-bridge-01` |
| WordPress | `news-wp-01` |
| MySQL | `news-db-01` |
| Redis | `news-redis-01` |
| Nginx LB | `news-lb-01` |
Cloudflare sits in front of the load balancer.