Tests / writer-pipeline tests (push) Failing after 5s
Tests / bridge tests (push) Failing after 6s
Tests / frontend lib tests (push) Successful in 14s
Tests / writer-pipeline tests (pull_request) Successful in 11s
Tests / bridge tests (pull_request) Successful in 13s
Tests / frontend lib tests (pull_request) Successful in 14s
Add site-scoped WP credentials (NEWSPROJECT_* vs ANDEBOL_*), RSS sources config, systemd oneshot/timer offset from andebol, env template, and deployment docs so BIT-22288 covers both stacks. Co-authored-by: Cursor <[email protected]>
345 lines
19 KiB
Markdown
345 lines
19 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*.
|
||
|
||
---
|
||
|
||
## Cloudflare — HTML edge cache (Cache Rules)
|
||
|
||
Public HTML is served through Cloudflare. **Default behaviour:** Cloudflare marks HTML as **not eligible** for the edge cache unless a **Cache Rule** says otherwise, so responses stay `cf-cache-status: DYNAMIC` even when the origin sends `Cache-Control: s-maxage=60, stale-while-revalidate=300` (see [`docs/PERFORMANCE_BASELINE.md`](PERFORMANCE_BASELINE.md) § *Remaining Gap — Cloudflare HTML Caching*).
|
||
|
||
This is **board / DevOps configuration** in the Cloudflare dashboard (or API/Terraform) for **each zone** that fronts a news-platform hostname — today **`andebol.net`** and **`newsproject.bitreport.pt`**. Repeat the same rule on both zones if they use separate zones.
|
||
|
||
### Dashboard (canonical)
|
||
|
||
1. Cloudflare dashboard → select the **zone** → **Caching** → **Cache Rules** → **Create rule**.
|
||
2. **Rule name:** e.g. `News platform — cache HTML (respect origin)`.
|
||
3. **When incoming requests match** — **Custom filter expression** (Expression Editor). Use **one rule per zone**; expressions below mirror [BIT-21847](/BIT/issues/BIT-21847) (exclude `wp-admin`, `wp-login`, `wp-json`, **`/api/`**).
|
||
|
||
**Zone `andebol.net`:**
|
||
|
||
```txt
|
||
(http.request.method eq "GET") and
|
||
(http.host in {"andebol.net" "www.andebol.net"}) and
|
||
not (http.request.uri.path contains "/wp-admin") and
|
||
not (http.request.uri.path contains "/wp-login.php") and
|
||
not (http.request.uri.path contains "/wp-json/") and
|
||
not (http.request.uri.path contains "/api/")
|
||
```
|
||
|
||
**Zone `newsproject.bitreport.pt`:**
|
||
|
||
```txt
|
||
(http.request.method eq "GET") and
|
||
(http.host eq "newsproject.bitreport.pt") and
|
||
not (http.request.uri.path contains "/wp-admin") and
|
||
not (http.request.uri.path contains "/wp-login.php") and
|
||
not (http.request.uri.path contains "/wp-json/") and
|
||
not (http.request.uri.path contains "/api/")
|
||
```
|
||
|
||
Use **`contains`** for path prefixes above (not `starts_with`) so expressions stay valid on **Cloudflare Free** (see `deploy/scripts/cf-cache-rules-apply.sh` notes from BIT-21912).
|
||
|
||
Extend the hostname list when new production hostnames are added under `config/domains/*.json`. The **`/api/`** exclusion reserves any future first-party API surface on the public hostname from edge HTML caching; adjust if a path must remain cacheable.
|
||
|
||
4. **Then** (cache settings):
|
||
|
||
- **Cache eligibility:** **Eligible for cache** (this is the supported replacement for the legacy Page Rule “Cache Everything” for HTML; see Cloudflare’s doc [*Cache Level (Cache Everything)*](https://developers.cloudflare.com/cache/how-to/cache-rules/examples/cache-everything/)).
|
||
- **Edge TTL / origin behaviour:** Prefer honouring origin `Cache-Control` / `s-maxage`. On some plans, HTML may still not edge-cache until **Edge TTL** is set (e.g. **override origin, 60 s**) in the same rule — the checked-in **`deploy/scripts/cf-cache-rules-apply.sh`** encodes what worked in production for BIT-21912. Re-evaluate if you upgrade plan or change cache semantics.
|
||
|
||
5. **Ordering:** place any **Bypass cache** rules (preview, authenticated staff, debug) **above** this rule so they win first.
|
||
|
||
6. **Purge after deploys:** continue to use the existing bridge / WordPress invalidation path (`docs/architecture.md` § *Cache Invalidation*). After material HTML or config changes, purge affected URLs or prefixes in Cloudflare if the edge still serves stale content beyond `s-maxage`.
|
||
|
||
### Verification (operator)
|
||
|
||
The cache rule matches **`GET`** only. **`curl -I` / `HEAD`** often shows **`cf-cache-status: DYNAMIC`** even when full **`GET`** responses are **`HIT`** — always verify with **GET** (body discarded):
|
||
|
||
```bash
|
||
curl -fsS "https://andebol.net/" -D - -o /dev/null | tr -d '\r' | egrep -i '^(cf-cache-status|cache-control|age):'
|
||
curl -fsS "https://andebol.net/" -D - -o /dev/null | tr -d '\r' | egrep -i '^(cf-cache-status|cache-control|age):'
|
||
```
|
||
|
||
Expect `cf-cache-status: HIT`, `EXPIRED`, `STALE`, or `REVALIDATED` on the repeat (not bare `MISS` every time once warm), and `cache-control` from origin unchanged. If both passes stay **`DYNAMIC`** on **GET**, the rule is missing, disabled, or superseded by a higher-priority bypass rule.
|
||
|
||
---
|
||
|
||
## 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`
|
||
- [ ] **Cloudflare (board):** per zone, Cache Rule for HTML edge cache (section **Cloudflare — HTML edge cache** above); verify `cf-cache-status` flips from `DYNAMIC` to `HIT` on repeat `GET` to `/`
|
||
|
||
---
|
||
|
||
## 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.
|
||
|
||
---
|
||
|
||
## Writer Pipeline — andebol.net (systemd timer)
|
||
|
||
The writer pipeline runs as a `oneshot` systemd service triggered daily at 06:00 UTC.
|
||
|
||
### Files
|
||
|
||
| Repo path | CT destination |
|
||
|-----------|----------------|
|
||
| `deploy/systemd/news-writer-andebol.service` | `/etc/systemd/system/news-writer-andebol.service` |
|
||
| `deploy/systemd/news-writer-andebol.timer` | `/etc/systemd/system/news-writer-andebol.timer` |
|
||
| `deploy/systemd/writer-andebol.env.example` | `/etc/news-platform/writer-andebol.env` (fill secrets) |
|
||
|
||
### Install on the CT
|
||
|
||
```bash
|
||
# 1. Copy env template and fill in WP credentials
|
||
sudo cp /opt/news-platform/deploy/systemd/writer-andebol.env.example \
|
||
/etc/news-platform/writer-andebol.env
|
||
sudo chmod 640 /etc/news-platform/writer-andebol.env
|
||
sudo chown root:www-data /etc/news-platform/writer-andebol.env
|
||
# Edit ANDEBOL_WP_USER and ANDEBOL_WP_APP_PASSWORD
|
||
|
||
# 2. Install units
|
||
sudo cp /opt/news-platform/deploy/systemd/news-writer-andebol.service \
|
||
/etc/systemd/system/
|
||
sudo cp /opt/news-platform/deploy/systemd/news-writer-andebol.timer \
|
||
/etc/systemd/system/
|
||
sudo systemctl daemon-reload
|
||
|
||
# 3. Enable and start the timer
|
||
sudo systemctl enable --now news-writer-andebol.timer
|
||
|
||
# 4. Verify
|
||
systemctl list-timers news-writer-andebol.timer
|
||
```
|
||
|
||
### Manual test run
|
||
|
||
```bash
|
||
sudo systemctl start news-writer-andebol.service
|
||
journalctl -u news-writer-andebol.service -n 50
|
||
```
|
||
|
||
### Log tailing
|
||
|
||
```bash
|
||
journalctl -f -u news-writer-andebol.service
|
||
```
|
||
|
||
Cycle output (metrics JSON) is also appended to `/opt/news-platform/writer-pipeline/var/metrics.jsonl`.
|
||
|
||
---
|
||
|
||
## Writer Pipeline — newsproject.bitreport.pt (systemd timer)
|
||
|
||
Same `run-cycle.js` binary as andebol.net, with **`--site newsproject.bitreport.pt`** and WordPress credentials from **`NEWSPROJECT_WP_*`** env vars (defaults to `http://127.0.0.1:8080/wp-json`). Source list: `writer-pipeline/config/newsproject.bitreport.pt.sources.json`.
|
||
|
||
The timer is offset from the andebol unit (**06:45** vs **06:00**) to reduce concurrent writes to the shared `var/aggregated-items.json` store.
|
||
|
||
### Files
|
||
|
||
| Repo path | CT destination |
|
||
|-----------|----------------|
|
||
| `deploy/systemd/news-writer-newsproject.service` | `/etc/systemd/system/news-writer-newsproject.service` |
|
||
| `deploy/systemd/news-writer-newsproject.timer` | `/etc/systemd/system/news-writer-newsproject.timer` |
|
||
| `deploy/systemd/writer-newsproject.env.example` | `/etc/news-platform/writer-newsproject.env` (fill secrets) |
|
||
|
||
### Install on the CT
|
||
|
||
```bash
|
||
sudo cp /opt/news-platform/deploy/systemd/writer-newsproject.env.example \
|
||
/etc/news-platform/writer-newsproject.env
|
||
sudo chmod 640 /etc/news-platform/writer-newsproject.env
|
||
sudo chown root:www-data /etc/news-platform/writer-newsproject.env
|
||
# Edit NEWSPROJECT_WP_USER and NEWSPROJECT_WP_APP_PASSWORD
|
||
|
||
sudo cp /opt/news-platform/deploy/systemd/news-writer-newsproject.service \
|
||
/etc/systemd/system/
|
||
sudo cp /opt/news-platform/deploy/systemd/news-writer-newsproject.timer \
|
||
/etc/systemd/system/
|
||
sudo systemctl daemon-reload
|
||
sudo systemctl enable --now news-writer-newsproject.timer
|
||
```
|
||
|
||
### Manual test run
|
||
|
||
```bash
|
||
sudo systemctl start news-writer-newsproject.service
|
||
journalctl -u news-writer-newsproject.service -n 50
|
||
```
|
||
|
||
---
|
||
|
||
## 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.
|