Files
traefik/README.md
T

282 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Traefik reverse proxy stack
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
- [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
## 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 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)), 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
# or using the CLI-flag static config variant:
docker compose -f compose.command.yaml --env-file .env up -d
```
## Layout
```
.
├── .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 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
```
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
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 | 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:
```bash
# Install apache2-utils / httpd-tools if needed, then:
htpasswd -nbB admin 'your-strong-password'
```
Paste the output into `TRAEFIK_CONSOLE_AUTH`. When storing inside a `.env` file for Docker Compose, escape literal `$` characters as `$$`.
## Ports
| Host (env / default) | Container | Role |
| --- | --- | --- |
| `${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 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` 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
Because `TRAEFIK_ACME` is a host bind mount outside the git checkout, certificate state persists across container recreations and Dockhand git redeploys.
## Dashboard & healthcheck
- **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 backend services to the same external Docker network (`NETWORK_NAME`), enable Traefik, and attach file-provider middlewares with `@file`:
```yaml
services:
myapp:
image: myapp:latest
networks:
- 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
- traefik.http.routers.myapp.middlewares=security-supermax@file,gzip@file
- traefik.http.services.myapp.loadbalancer.server.port=8080
networks:
docknet:
external: true
name: docknet
```
Chain multiple middlewares with commas. File-provider names resolve as `<name>@file`.
## Middleware catalog
Defined in [`traefik/conf.d/middlewares.yaml`](./traefik/conf.d/middlewares.yaml).
### Security chains (pick one)
| Middleware | Intent |
| --- | --- |
| `default` | CSP strict + frame deny + gzip + HSTS + baseline security headers |
| `secure-all` | Permissive CSP + same-origin frames + HSTS + security headers |
| `security-mallcop` | Open referrer + open CSP + HSTS + security headers |
| `security-lax` | Lax referrer + lax CSP + HSTS + security headers |
| `security-medium` | Permissive referrer/CSP + same-origin frames + HSTS + security headers |
| `security-prison` | Medium referrer + balanced CSP + same-origin frames + HSTS + security headers |
| `security-supermax` | No-referrer + strict CSP + frame deny + HSTS + security headers |
| `security-supermax-with-analytics` | Supermax plus GA/Clarity/Umami-friendly CSP and COOP |
### CSP building blocks
| Middleware | Notes |
| --- | --- |
| `csp-open-header` | Very permissive (legacy / hard-to-lock apps) |
| `csp-lax-header` | Self + common inline/eval allowances |
| `csp-permissive-header` | Self-focused with inline/eval for scripts/styles |
| `csp-balanced-header` | Self + common CDNs (jsDelivr, cdnjs, unpkg, Google Fonts) |
| `csp-strict-header` | Self-only |
| `csp-strict-header-with-ga` | Strict plus analytics/Clarity/GTM endpoints |
### Other headers & utilities
| Middleware | Role |
| --- | --- |
| `security-headers` | `X-Content-Type-Options: nosniff`, disables legacy `X-XSS-Protection` |
| `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` |
| `gzip` | Response compression |
| `referrer-*-header` | Referrer-Policy tiers (`open` → `supermax`) |
| `strip-server-path` | Strips `/db`, `/server`, `/traefik` prefixes |
### Auth & access
| Middleware | Role |
| --- | --- |
| `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` | `ipAllowList` (edit `sourceRange` for your Linode/NAS/LAN IPs) |
### Redirects
| Middleware | Role |
| --- | --- |
| `redirect-www-to-non-www` | `www.` → apex |
| `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 `traefik/conf.d/middlewares.yaml` before deploying outside this environment.
## File-based routers and services
[`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
pnpm up # docker compose --env-file .env up -d
docker compose -f compose.command.yaml --env-file .env up -d
# Follow logs
pnpm logs # docker compose logs -f traefik
# 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 `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).
## Host setup checklist (Linode VPS / NAS)
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 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