Updates for portability and ensuring middleware survives

This commit is contained in:
mifi committed 2026-12-04 11:13:41 -03:00
1 parent 1ec52f0a75
commit e23d539733
10 files changed
+425 -79

No files matched your search

+133 -69
View File
@@ -1,58 +1,112 @@
# Traefik reverse proxy stack
Docker Compose stack for [Traefik](https://traefik.io/) with Let’s Encrypt (Cloudflare DNS challenge), a secured dashboard, and a reusable middleware library for security headers, CSP tiers, Authentik SSO, redirects, and IP allowlists.
Base Docker Compose stack for [Traefik](https://traefik.io/) used across Linode VPS and NAS server hosts as a git-based stack in [Dockhand](https://dockhand.pro/). Includes Let’s Encrypt TLS via Cloudflare DNS-01 challenge, a basic-auth secured dashboard, healthcheck ping, Woodpecker CI webhook redeploys, and a reusable middleware library for security headers, CSP tiers, Authentik SSO, redirects, and IP allowlists.
## Prerequisites
- Docker Engine with Compose v2
- A Cloudflare account with API access for the domains you terminate here
- DNS for those domains pointed at the host that runs this stack
- A shared Docker network that your backend services also join (default: `docknet`)
- [Dockhand](https://dockhand.pro/) (for git-based stack deployment) or Docker CLI access
- A pre-created shared external Docker network for Traefik and backend services (default: `docknet`):
```bash
docker network create docknet
```
- A pre-created persistent host directory for ACME certificate storage (`TRAEFIK_ACME`), because `compose.yaml` binds it with `create_host_path: false`:
```bash
mkdir -p /path/to/letsencrypt
```
- A Cloudflare account with API access for the domains served by the host
- DNS records for those domains pointed at the Linode VPS or NAS host running this stack
## Quick start
## Deploying with Dockhand (recommended)
1. In Dockhand, create a new **git-based stack** pointing to this repository (`main` branch) and either `compose.yaml` (file-based static config) or [`compose.command.yaml`](./compose.command.yaml) (CLI-flag static config).
2. Ensure the external Docker network (`NETWORK_NAME`, default `docknet`) and host ACME directory (`TRAEFIK_ACME`) already exist on the target host.
3. Configure the stack environment variables in Dockhand using [`example.env`](./example.env) (for `compose.yaml`) or [`example.command.env`](./example.command.env) (for `compose.command.yaml`) as the template — per-host values such as `CONSOLE_HOST`, `TRAEFIK_ACME`, and ports can differ between your Linode VPS and NAS.
4. Deploy the stack.
### Compose file variants
| File | Static config source | Env template | Notes |
| --- | --- | --- | --- |
| [`compose.yaml`](./compose.yaml) | [`traefik/traefik.yaml`](./traefik/traefik.yaml) (`--configFile`) | [`example.env`](./example.env) | Default file-based static config |
| [`compose.command.yaml`](./compose.command.yaml) | Inline `command:` CLI flags | [`example.command.env`](./example.command.env) | Lets `ACME_EMAIL` / `CLOUDFLARE_EMAIL`, `NETWORK_NAME`, and `TRAEFIK_LOG_LEVEL` come from env vars; does not mount `traefik.yaml` |
| [`compose.future.yaml`](./compose.future.yaml) | [`traefik/traefik.yaml`](./traefik/traefik.yaml) (`--configFile`) | [`example.env`](./example.env) | Candidate hardened stack (`no-new-privileges:true`, scoped `CLOUDFLARE_DNS_API_TOKEN`, no host `:8080`) |
### Automated redeploys (Woodpecker CI)
[`.woodpecker/deploy.yaml`](./.woodpecker/deploy.yaml) triggers on `push`, `tag`, and `manual` events on `main` (or `deployment` events targeting `production`):
- Signs an empty JSON payload (`{}`) with `DOCKHAND_WEBHOOK_SECRET` (`X-Hub-Signature-256`) and sends a `POST` request to `DOCKHAND_WEBHOOK_URL` to trigger a Dockhand stack redeploy.
- Sends build success/failure notifications to Mattermost (`MATTERMOST_BOT_ACCESS_TOKEN`, `MATTERMOST_CHANNEL_ID`, `MATTERMOST_POST_API_URL`).
## Quick start (CLI)
```bash
git clone <this-repo> traefik && cd traefik
git clone ssh://git@git.mifi.dev:12022/mifi-holdings/traefik.git && cd traefik
cp example.env .env
# or for compose.command.yaml:
# cp example.command.env .env
```
Edit `.env` (see [Environment variables](#environment-variables)), then:
Edit `.env` (see [Environment variables](#environment-variables)), verify the pre-created network and `TRAEFIK_ACME` directory exist, then start the stack:
```bash
docker compose --env-file .env up -d
```
# or via package.json scripts:
pnpm up
Traefik will join (or create) the Docker network named by `NETWORK_NAME`, watch containers on that host for Traefik labels, and issue certificates via Cloudflare DNS. ACME data is stored in the Docker named volume `traefik-acme` (created automatically; no manual file setup).
# or using the CLI-flag static config variant:
docker compose -f compose.command.yaml --env-file .env up -d
```
## Layout
```
.
├── compose.yml # Traefik service, ports, dashboard labels, ACME volume
├── example.env # Env template (copy to .env)
├── .woodpecker/
│ └── deploy.yaml # CI pipeline: signed Dockhand webhook + Mattermost alerts
├── compose.yaml # Default Traefik stack (static config via traefik.yaml)
├── compose.command.yaml # Alternate Traefik stack (static config via CLI flags / env vars)
├── compose.future.yaml # Candidate hardened compose (no-new-privileges, scoped DNS token, no :8080)
├── example.env # Environment variable template for compose.yaml
├── example.command.env # Environment variable template for compose.command.yaml
├── package.json # Stack metadata and Docker Compose helper scripts
└── traefik/
├── traefik.yaml # Static config: entrypoints, providers, TLS SANs
└── conf.d/
├── middlewares.yaml # Shared middleware library
├── routers.yaml # Optional file-based routers
└── services.yaml # Optional file-based services
├── traefik.yaml # Static config for compose.yaml / compose.future.yaml
├── conf.d/ # Base dynamic config (always mounted at /etc/traefik/conf.d/base)
│ ├── middlewares.yaml # Shared middleware library
│ ├── routers.yaml # Optional shared file-based routers (stub)
│ └── services.yaml # Optional shared file-based services (stub)
└── conf.local/ # Default empty local override dir (mounted at /etc/traefik/conf.d/local)
└── .gitkeep
```
Static config lives in `traefik/traefik.yaml`. Dynamic config (middlewares, optional routers/services) is loaded from `traefik/conf.d/` and hot-reloads when files change. Certificate state lives in the `traefik-acme` volume, not in the repo.
For `compose.yaml` and `compose.future.yaml`, static config lives in [`traefik/traefik.yaml`](./traefik/traefik.yaml). For [`compose.command.yaml`](./compose.command.yaml), static config is passed via `command:` CLI flags so `ACME_EMAIL`, `NETWORK_NAME`, and `TRAEFIK_LOG_LEVEL` can be set per host via environment variables without mounting `traefik.yaml`. In all variants, dynamic config is loaded recursively from `/etc/traefik/conf.d` and hot-reloads on file changes:
- **`/etc/traefik/conf.d/base`** always mounts [`./traefik/conf.d`](./traefik/conf.d) from this repository (shared middlewares and base config).
- **`/etc/traefik/conf.d/local`** mounts `${TRAEFIK_CONFD:-./traefik/conf.local}` for host-specific routers, services, or middlewares on a given Linode VPS or NAS host.
## Environment variables
Copy `example.env` to `.env` and fill in real values:
Configure these in Dockhand’s stack environment or in a local `.env` copied from [`example.env`](./example.env) (or [`example.command.env`](./example.command.env) for `compose.command.yaml`):
| Variable | Purpose |
| --- | --- |
| `CLOUDFLARE_EMAIL` | Cloudflare account email (ACME + API) |
| `CLOUDFLARE_API_KEY` | Cloudflare Global API Key (or scoped token with DNS edit) |
| `CONSOLE_HOST` | Hostname for the Traefik dashboard (e.g. `traefik.example.com`) |
| `NETWORK_NAME` | Docker network name shared with backends (default `docknet`) |
| `TRAEFIK_CONSOLE_AUTH` | Basic-auth users for the dashboard (`htpasswd` format) |
| `TRAEFIK_YAML` | Host path to static config (default `./traefik/traefik.yaml`) |
| `TRAEFIK_CONFD` | Host path to dynamic config dir (default `./traefik/conf.d`) |
| Variable | Required | Default | Purpose |
| --- | --- | --- | --- |
| `TRAEFIK_ACME` | Yes | — | Existing host directory bind-mounted to `/letsencrypt` for `acme.json` |
| `CONSOLE_HOST` | Yes | — | Hostname for the Traefik dashboard (e.g. `traefik.mifi.dev`) |
| `TRAEFIK_CONSOLE_AUTH` | Yes | — | Basic-auth users for the dashboard (`htpasswd` format) |
| `CLOUDFLARE_EMAIL` | Yes (`compose.yaml`, `compose.command.yaml`) | — | Cloudflare account email for DNS-01 challenge (also default ACME email in `compose.command.yaml`) |
| `CLOUDFLARE_API_KEY` | Yes (`compose.yaml`, `compose.command.yaml`) | — | Cloudflare Global API Key |
| `ACME_EMAIL` | No (`compose.command.yaml` only) | `${CLOUDFLARE_EMAIL}` | Optional ACME registration email override when different from `CLOUDFLARE_EMAIL` |
| `TRAEFIK_LOG_LEVEL` | No (`compose.command.yaml` only) | `INFO` | Traefik static log level (`DEBUG`, `INFO`, `WARN`, `ERROR`) |
| `TRAEFIK_IMAGE` | No | `traefik:latest` | Traefik Docker image tag |
| `NETWORK_NAME` | No | `docknet` | Pre-existing external Docker network shared with backends (also drives `--providers.docker.network` in `compose.command.yaml`) |
| `TRAEFIK_YAML` | No (`compose.yaml`, `compose.future.yaml`) | `./traefik/traefik.yaml` | Host path to static config (unused by `compose.command.yaml`) |
| `TRAEFIK_CONFD` | No | `./traefik/conf.local` | Host path for local dynamic config mounted at `/etc/traefik/conf.d/local` (do not set to `./traefik/conf.d`) |
| `TRAEFIK_HTTP_PORT` | No | `8342` | Host port mapped to container `:80` |
| `TRAEFIK_HTTPS_PORT` | No | `8767` | Host port mapped to container `:443` |
| `TRAEFIK_DASHBOARD_PORT` | No | `8080` | Host port mapped to container `:8080` |
| `CLOUDFLARE_DNS_API_TOKEN` | Yes (`compose.future.yaml`) | — | Scoped Cloudflare DNS edit token (replaces email + global key in `compose.future.yaml`) |
Generate dashboard credentials:
@@ -61,40 +115,41 @@ Generate dashboard credentials:
htpasswd -nbB admin 'your-strong-password'
```
Paste the output into `TRAEFIK_CONSOLE_AUTH`. If the value contains `$`, escape them for Compose (use `$$`) or quote carefully in `.env`.
Paste the output into `TRAEFIK_CONSOLE_AUTH`. When storing inside a `.env` file for Docker Compose, escape literal `$` characters as `$$`.
## Ports
| Host | Container | Role |
| Host (env / default) | Container | Role |
| --- | --- | --- |
| `8342` | `80` | HTTP → redirects to HTTPS |
| `8767` | `443` | HTTPS |
| `8080` | `8080` | Traefik API / dashboard (also exposed via `CONSOLE_HOST` with TLS + basic auth) |
| `${TRAEFIK_HTTP_PORT:-8342}` | `80` (`web`) | HTTP → redirects to `websecure` (`https`) |
| `${TRAEFIK_HTTPS_PORT:-8767}` | `443` (`websecure`) | HTTPS with `letsencrypt` cert resolver |
| `${TRAEFIK_DASHBOARD_PORT:-8080}` | `8080` (`traefik`) | Internal `traefik` entrypoint (used by `ping` healthcheck) |
Point your public reverse path or firewall at `8767` (and `8342` if you want HTTP→HTTPS at the edge). Adjust the left-hand ports in `compose.yml` if you prefer `80`/`443` on the host.
Point your public reverse proxy, port-forward, or firewall at `TRAEFIK_HTTPS_PORT` (and `TRAEFIK_HTTP_PORT` for HTTP→HTTPS redirects), or override those env vars to `80` / `443` on hosts where Traefik binds privileged ports directly.
> `compose.future.yaml` removes the host `:8080` port mapping so the `traefik` entrypoint stays container-internal while the dashboard remains reachable over `websecure` at `CONSOLE_HOST`.
## TLS and certificates
- Challenge: **DNS-01** via Cloudflare (`certificatesResolvers.letsencrypt`)
- Storage: Docker named volume `traefik-acme` mounted at `/letsencrypt` (Traefik creates `acme.json` on first run)
- Default certificate SANs for the TLS store are defined under `tls.stores.default` in `traefik/traefik.yaml` — edit that list for your domains
- **Challenge:** DNS-01 via Cloudflare (`certificatesResolvers.letsencrypt` in [`traefik/traefik.yaml`](./traefik/traefik.yaml) or CLI flags in [`compose.command.yaml`](./compose.command.yaml), DNS resolvers `1.1.1.1:53` and `1.0.0.1:53`)
- **ACME email:** configured in `traefik/traefik.yaml` (`certificatesResolvers.letsencrypt.acme.email`) for `compose.yaml` / `compose.future.yaml`, or via `${ACME_EMAIL:-${CLOUDFLARE_EMAIL}}` in `compose.command.yaml`
- **Storage:** bind-mounted host directory `${TRAEFIK_ACME}` → `/letsencrypt` (`acme.json` is written inside that directory)
- **Certificate issuance:** `websecure` configures `http.tls.certResolver: letsencrypt` so certificates are requested per router `Host(...)` rule
The volume survives `docker compose down` / `up`. Prefer `docker compose down` over `docker compose down -v` unless you intentionally want to wipe certs (which will re-hit Let’s Encrypt rate limits).
Because `TRAEFIK_ACME` is a host bind mount outside the git checkout, certificate state persists across container recreations and Dockhand git redeploys.
Ensure Cloudflare credentials can create/delete `_acme-challenge` TXT records for every zone you serve.
## Dashboard & healthcheck
## Dashboard
The dashboard is enabled and routed with Docker labels on the Traefik container:
- URL: `https://<CONSOLE_HOST>/`
- Entrypoint: `websecure`
- Auth: middleware `traefik-auth` (basic auth from `TRAEFIK_CONSOLE_AUTH`)
- Certificate: Let’s Encrypt via `letsencrypt` resolver
- **URL:** `https://<CONSOLE_HOST>/`
- **Entrypoint:** `websecure`
- **Auth:** Docker-label middleware `traefik-auth` (basic auth from `TRAEFIK_CONSOLE_AUTH`)
- **Certificate:** Let’s Encrypt via `letsencrypt`
- **API mode:** `api.dashboard: true`, `api.insecure: false`
- **Healthcheck:** `traefik healthcheck --ping` against the `traefik` (`:8080`) entrypoint every `30s`
## Using middlewares on your services
Connect apps to the same Docker network (`NETWORK_NAME`), enable Traefik, and attach middlewares by name with the `@file` provider:
Connect backend services to the same external Docker network (`NETWORK_NAME`), enable Traefik, and attach file-provider middlewares with `@file`:
```yaml
services:
@@ -104,6 +159,7 @@ services:
- docknet
labels:
- traefik.enable=true
- traefik.docker.network=docknet
- traefik.http.routers.myapp.rule=Host(`app.example.com`)
- traefik.http.routers.myapp.entrypoints=websecure
- traefik.http.routers.myapp.tls.certresolver=letsencrypt
@@ -120,7 +176,7 @@ Chain multiple middlewares with commas. File-provider names resolve as `<name>@f
## Middleware catalog
Defined in `traefik/conf.d/middlewares.yaml`.
Defined in [`traefik/conf.d/middlewares.yaml`](./traefik/conf.d/middlewares.yaml).
### Security chains (pick one)
@@ -151,7 +207,8 @@ Defined in `traefik/conf.d/middlewares.yaml`.
| Middleware | Role |
| --- | --- |
| `security-headers` | `X-Content-Type-Options: nosniff`, disables legacy `X-XSS-Protection` |
| `hsts-header` | HSTS 2y, includeSubDomains, preload |
| `hsts-standard` | HSTS 1y (`stsSeconds: 31536000`) |
| `hsts-strict` | HSTS 2y (`stsSeconds: 63072000`), `stsIncludeSubdomains`, `stsPreload` |
| `frame-deny-header` | `X-Frame-Options: DENY` |
| `frame-sameorigin-header` | `X-Frame-Options: SAMEORIGIN` |
| `cross-origin-opener-strict-policy` | `Cross-Origin-Opener-Policy: same-origin` |
@@ -166,7 +223,7 @@ Defined in `traefik/conf.d/middlewares.yaml`.
| `authentik-outpost` | ForwardAuth to Authentik outpost (`outpost.mifi.holdings`) |
| `authentik-no-cache` | Disable caching on Authentik responses |
| `authentik-static-immutable` | Long-cache immutable static assets |
| `internal-ips` | IP allowlist (edit `sourceRange` for your networks) |
| `internal-ips` | `ipAllowList` (edit `sourceRange` for your Linode/NAS/LAN IPs) |
### Redirects
@@ -176,42 +233,49 @@ Defined in `traefik/conf.d/middlewares.yaml`.
| `redirect-non-www-to-www` | apex → `www.` |
| `redirect-postfixadmin` | Mail settings path redirect (site-specific) |
Update Authentik outpost URL, IP allowlists, and domain-specific redirects in `middlewares.yaml` before deploying outside this environment.
Update Authentik outpost URL, IP allowlists, and domain-specific redirects in `traefik/conf.d/middlewares.yaml` before deploying outside this environment.
## File-based routers and services
`traefik/conf.d/routers.yaml` and `services.yaml` are stubs for optional non-Docker backends. Uncomment or add entries when you need host/path rules that are not expressed as container labels.
[`traefik/conf.d/routers.yaml`](./traefik/conf.d/routers.yaml) and [`traefik/conf.d/services.yaml`](./traefik/conf.d/services.yaml) are stubs for shared non-Docker backends. For host-specific routers or services (for example, NAS-only or VPS-only backends) without diverging from the git repository, put YAML files in a host directory and set `TRAEFIK_CONFD` to that path (mounted at `/etc/traefik/conf.d/local` alongside the repo's `/etc/traefik/conf.d/base`).
## Operations
Use Dockhand’s stack controls, standard `docker compose` commands, or the shortcuts in [`package.json`](./package.json):
```bash
# Validate rendered Compose config
pnpm validate # docker compose --env-file .env config --quiet
pnpm config:future # docker compose -f compose.future.yaml --env-file .env config
docker compose -f compose.command.yaml --env-file .env config --quiet
# Start / recreate after config or .env changes
docker compose --env-file .env up -d
pnpm up # docker compose --env-file .env up -d
docker compose -f compose.command.yaml --env-file .env up -d
# Follow logs
docker compose logs -f traefik
pnpm logs # docker compose logs -f traefik
# Stop (keeps the ACME volume)
docker compose down
# Inspect ACME volume location (optional)
docker volume inspect traefik_traefik-acme
# Pull updated image / restart / stop
pnpm pull # docker compose pull
pnpm restart # docker compose --env-file .env restart
pnpm down # docker compose down
```
Dynamic files under `conf.d/` reload without a full restart. Changes to `traefik.yaml`, Compose labels, ports, or env vars generally need `docker compose up -d` (or a container recreate).
Dynamic files under `traefik/conf.d/` and `TRAEFIK_CONFD` reload without a full restart. Changes to `traefik/traefik.yaml`, `compose.command.yaml` CLI flags, Compose labels, ports, or env vars generally require recreating the container (`docker compose --env-file .env up -d` or a Dockhand redeploy).
## Customization checklist
## Host setup checklist (Linode VPS / NAS)
1. Set `.env` from `example.env` and generate `TRAEFIK_CONSOLE_AUTH`
2. Edit TLS SANs in `traefik/traefik.yaml` for your domains
3. Adjust `internal-ips` and Authentik URLs in `middlewares.yaml`
4. Ensure backends use `traefik.enable=true` and join `NETWORK_NAME`
5. Publish host ports (`8342`/`8767`) as needed for your network edge
1. Create the external Docker network: `docker network create docknet`
2. Create a persistent ACME directory on the host (e.g. `mkdir -p /srv/traefik/letsencrypt`)
3. Set all required env vars in Dockhand (or `.env`), including `TRAEFIK_ACME`, `CONSOLE_HOST`, `TRAEFIK_CONSOLE_AUTH`, and Cloudflare credentials
4. If using `compose.yaml`, update `acme.email` in `traefik/traefik.yaml` (or use `compose.command.yaml` to set `ACME_EMAIL` / `CLOUDFLARE_EMAIL` via env); update `internal-ips` / Authentik URLs in `traefik/conf.d/middlewares.yaml` as needed
5. Ensure backend containers join `NETWORK_NAME` and set `traefik.enable=true`
6. Open/forward `TRAEFIK_HTTP_PORT` and `TRAEFIK_HTTPS_PORT` at your firewall or edge router
## Security notes
- Do not commit `.env` or real API keys
- Prefer a scoped Cloudflare API token limited to DNS edit on required zones when possible
- Keep the dashboard behind strong basic auth (and consider further restricting with `internal-ips` or Authentik)
- Prefer moving to `compose.future.yaml` (or adopting `no-new-privileges:true`, removing host `:8080`, and switching to a scoped `CLOUDFLARE_DNS_API_TOKEN`) once ready
- Keep the dashboard behind strong basic auth (and consider further restricting with `internal-ips` or `authentik-outpost`)
- Review CSP chains per app; start stricter and loosen only where breakage requires it
- Do not use `docker compose down -v` in production unless you mean to discard certificates