diff --git a/.deprecated/README.md b/.deprecated/README.md index 50c5aa6..464d3d0 100644 --- a/.deprecated/README.md +++ b/.deprecated/README.md @@ -32,3 +32,7 @@ Watchdog that restarted any container docker marked `unhealthy` (only `backend` and `python` define healthchecks). It mounts the docker socket, which is effectively root on the host. To bring it back, layer `docker-compose.autoheal.yml` the same way as above. + +Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers +labelled `autoheal=true` (nginx). This copy is the old `all` variant, kept for +reference. diff --git a/CLAUDE.md b/CLAUDE.md index 6f3deb5..c63fe3b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun **Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). nginx serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7. -**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. +**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. nginx runs one worker per CPU and has a healthcheck (`/nginx-health` on :80); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated in nginx because a crawler swarm hammers them; the branch views stay public. ## Backend Structure diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 79cb8ef..4570449 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -69,6 +69,7 @@ backend icecast2 gitea sb sb-pub python | | | cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) | | dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no | | traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no | +| autoheal (restarts unhealthy nginx) | `autoheal` | — (no network) | none; reads the Docker socket | no | | garage (S3 object store) | `garage` | 3900 S3, 3902 web, 3903 admin | none directly; `/uploads/` falls back to its web endpoint for files not on the volume | no | | garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by nginx `auth_request`) | no | @@ -88,7 +89,9 @@ in one step — never change one without the other.** - **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with `resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a backend down (502s until it appears) instead of refusing to start. -- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/` and `/uploads/private/` are +- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and + Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the + branch views stay public) are protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure redirects to the SPA login. Most of these services have no auth of their own at that path; the job and activity trackers also check the session themselves. Their carve-outs, which a session @@ -610,10 +613,27 @@ icecast source password. liquidsoap pre-empts the fallback playlist immediately silence. Adding MP3s to `icecast2/fallback_music/` is picked up live (`reload_mode="watch"`) with no restart. -**Unhealthy containers are not restarted automatically.** `backend` and `python` -define healthchecks, but the `autoheal` watchdog that acted on them was retired -(`.deprecated/autoheal`), so `unhealthy` is only visible in `docker ps`. -`restart: always` still brings back a container whose process exits. +**Only nginx is restarted when unhealthy.** Docker marks a container +`unhealthy` but never acts on it; `restart: always` only brings back a process +that exits. The `autoheal` container restarts anything labelled +`autoheal=true`, which today is just nginx (its healthcheck fetches +`/nginx-health` on :80 every 30s; three misses, about 90s, and it is +restarted). `backend` and `python` also define healthchecks, but carry no +label, so for them `unhealthy` is only visible in `docker ps`. Add the label to +cover another service. + +**Site down but every container `Up`.** That is what a stalled nginx worker +looks like (2026-10-19: 4.6 hours, every tunnel request a `TLS handshake +timeout` in `docker logs cloudflared`, and the Cloudflare dashboard still +showing the tunnel healthy, since that only covers the tunnel's own link). The +healthcheck should now catch it. If it recurs, capture the stuck worker before +restarting, since a restart destroys the only evidence of why: + +``` +docker inspect nginx --format '{{.State.Health.Status}}' +docker top nginx -o pid,stat,wchan:30,etime,cmd # what each worker is waiting in +docker compose restart nginx +``` --- diff --git a/docker-compose.yml b/docker-compose.yml index e809962..d8cda07 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -156,6 +156,21 @@ services: # it survives rebuilds and the `traffic` container can tail it. Grows # without bound unless rotated — see DEPLOYMENT.md. - ./logs/nginx:/var/log/nginx/payloads + # restart: always only acts when nginx's master exits. On 2026-10-19 the + # worker stalled while the master lived, and the site was down 4.6 hours + # with the container "Up". /nginx-health is answered by a worker, so a + # stall shows here; Docker only marks it unhealthy, and the `autoheal` + # label is what gets it restarted (see the autoheal service). Plain HTTP + # on :80 so it also passes in the first-boot setup config, which has no + # :443; the workers that serve :80 are the ones serving TLS. + healthcheck: + test: ["CMD", "curl", "-fsS", "--max-time", "5", "-o", "/dev/null", "http://127.0.0.1/nginx-health"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 30s + labels: + - autoheal=true # Obtains the cert once, then renews every 12h forever. Disabled in dev via # the `disabled` profile in docker-compose.dev.yml. Note this is the stock @@ -627,6 +642,33 @@ services: volumes: - /var/run/docker.sock:/var/run/docker.sock:ro + # Restarts any container labelled autoheal=true once Docker marks it + # unhealthy, which Docker itself never does (restart policies only see the + # process exit). Only nginx carries the label today; give it to another + # service with a healthcheck to cover that one too. It polls every 5s. + # + # It needs the Docker socket read-write to restart things, which is root on + # the host, so it gets no network at all: nothing can reach it, and it + # reaches nothing but the socket. For the same reason the image is pinned BY + # DIGEST, never a tag, so a push to Docker Hub cannot gain root here at the + # next pull. The digest is the multi-arch index of 1.2.0, the newest tagged + # release; it calls the API unversioned, so it keeps working as the engine's + # minimum API version moves. To bump: `docker buildx imagetools inspect + # willfarrell/autoheal:` and paste the top-level Digest. + # + # This is the watchdog retired on 2026-10-01 (.deprecated/autoheal), back + # with a label filter instead of `all`, so backend's and python's + # healthchecks stay informational. + autoheal: + image: willfarrell/autoheal@sha256:31f580ef0279eaced5b38d631b08c474d70d8403c1c2fdd6ddcf2e879d5f3f7c + container_name: autoheal + restart: always + network_mode: none + environment: + - AUTOHEAL_CONTAINER_LABEL=autoheal + volumes: + - /var/run/docker.sock:/var/run/docker.sock + # S3-compatible object store holding public uploads (the `uploads` bucket). # The backend writes to it on :3900 once S3_ENDPOINT is set in .env; nginx # serves /uploads/ from it anonymously on :3902, falling back to the diff --git a/nginx/nginx.conf.template b/nginx/nginx.conf.template index 582753a..d5bb82d 100644 --- a/nginx/nginx.conf.template +++ b/nginx/nginx.conf.template @@ -36,6 +36,15 @@ # (which carry the security headers), the `graphql` rate-limit zone and its # location, and the limit_req_zone declarations the shared routes refer to. # ============================================================================= + +# One worker per CPU. Unset, nginx runs a single worker, and on 2026-10-19 that +# one worker stalled for 4.6 hours: the master kept the container "Up" and the +# tunnel stayed connected, but every request timed out in the TLS handshake. +# With several workers a stuck one only loses the connections it holds; the +# others keep accepting. The healthcheck in docker-compose.yml (and autoheal +# restarting on it) covers the case where they all stall. +worker_processes auto; + events { worker_connections 1024; } @@ -179,6 +188,15 @@ http { root /var/www/certbot; } + # The container healthcheck's target (docker-compose.yml). Answered by + # nginx itself, so it measures whether a worker is serving and nothing + # upstream. Unlogged, or it would put a line in the payload log every + # 30s. Every config's default :80 server has one, setup and dev too. + location = /nginx-health { + access_log off; + return 204; + } + # Redirect everything else to HTTPS location / { return 301 https://www.$DOMAIN$request_uri; diff --git a/nginx/nginx_dev.conf.template b/nginx/nginx_dev.conf.template index c3efd9a..ac02e04 100644 --- a/nginx/nginx_dev.conf.template +++ b/nginx/nginx_dev.conf.template @@ -33,6 +33,10 @@ # annotated in nginx_routes.conf.template; the rate-limit reasoning is in # nginx.conf.template. # ============================================================================= + +# As in production; why is in nginx.conf.template. +worker_processes auto; + events { worker_connections 1024; } @@ -89,6 +93,13 @@ http { listen 80; server_name $DOMAIN www.$DOMAIN; + # The container healthcheck's target; see nginx.conf.template. Only in + # this block, as in production, where it sits in the :80 server too. + location = /nginx-health { + access_log off; + return 204; + } + include /etc/nginx/nginx_dev_common.conf; } diff --git a/nginx/nginx_routes.conf.template b/nginx/nginx_routes.conf.template index 1dae648..de28d44 100644 --- a/nginx/nginx_routes.conf.template +++ b/nginx/nginx_routes.conf.template @@ -270,6 +270,26 @@ proxy_set_header X-Forwarded-Proto $scheme; } + # Gitea's history views and archives, behind the admin gate. A crawler + # swarm (129k requests from 103k IPs over 2026-10-18/19, so per-IP rate + # limits are useless) walks every file at every commit, and those pages + # are the expensive ones: diffs, blame, tarballs nginx spools to disk. + # 89% of its requests were these shapes; people browsing the code use + # the branch views (src/branch/..., commits/branch/...), which stay + # public, so the CV's repo links still work. Gitea's own + # REQUIRE_SIGNIN_VIEW=expensive would also block src/branch, hence + # doing it here. A regex location, so it wins over /gitea/ above. + location ~ ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/) { + auth_request /internal/auth/admin-validate; + error_page 401 403 = @auth_denied; + rewrite ^/gitea/(.*)$ /$1 break; + proxy_pass $upstream_gitea; + 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; + } + location /notes { return 301 /notes/; } diff --git a/nginx/nginx_setup.conf.template b/nginx/nginx_setup.conf.template index 278b5e2..962252c 100644 --- a/nginx/nginx_setup.conf.template +++ b/nginx/nginx_setup.conf.template @@ -45,6 +45,12 @@ http { root /var/www/certbot; } + # The container healthcheck's target; see nginx.conf.template. + location = /nginx-health { + access_log off; + return 204; + } + # All other requests should return 404 location / { return 404;