Compare commits

..

12 Commits

Author SHA1 Message Date
gitea_admin 36fbaf171a Add firewall and home LAN access docs, ComfyUI image generation, and backup plan
Document the Hetzner Cloud Firewall posture (inbound from private/home only, outbound allow-all, egress-only IPv6, public IPs on workers) in a new `Cluster_admin/firewall.md` and reference it from `AGENTS.md`, `Environment.md`, and `README.md`. Update the Mailu README to note that SMTP/IMAP ports are not currently exposed.

Add `HomeAccess/` with a privileged DaemonSet and README that give cluster nodes a route to `192.168.8.0/24` via point-to-point GRE tunnels to the master and its WireGuard tunnel.

Wire Open WebUI to ComfyUI on pop-os through a new `openwebui-imagegen` ConfigMap consumed via `envFrom`, with migration notes covering the PersistentConfig DB override.

Bump kube-prometheus-stack to 88.6.1 with an 8GB `retentionSize` cap, grow the postgres PVC to 50Gi, and add a PostgreSQL backup plan for pg_dumpall/rclone streaming to a Hetzner Storage Box.
2026-12-01 12:36:14 +02:00
gitea_admin 975c059ecf Added Ollama LB Service 2026-08-27 11:22:03 +03:00
gitea_admin a8bc5f10e0 Add Ollama and Open WebUI deployment to Kubernetes and migration plan 2026-08-23 13:23:30 +03:00
gitea_admin 3efd718ac9 Add Environment.md and set Immich imagePullPolicy to Always 2026-07-31 11:01:34 +03:00
gitea_admin aeb8d56ec6 Add cluster node OS update runbook 2026-07-07 11:57:56 +03:00
gitea_admin 8b737f2cb2 Update pgvector to v0.8.4 and set imagePullPolicy to Always 2026-07-07 11:57:48 +03:00
gitea_admin b3772ea48a Remove PostgreSQL migration runbook 2026-07-07 11:18:55 +03:00
gitea_admin 3c46563099 Remove old PostgreSQL manifests 2026-07-07 11:18:40 +03:00
gitea_admin 923c6c8ec5 Add Mailu email server deployment via Helm chart 2026-07-07 11:18:24 +03:00
gitea_admin a3809d57a4 Moved docker images to project and updated database image 2026-07-06 15:24:54 +03:00
gitea_admin 3a8012e694 Added agent file 2026-07-06 14:27:30 +03:00
gitea_admin 93400ff998 Updated file struct 2026-07-06 14:07:20 +03:00
40 changed files with 2167 additions and 317 deletions
+16
View File
@@ -0,0 +1,16 @@
{
"mcpServers": {
"UnoApp": {
"command": "dotnet",
"args": [
"dnx",
"-y",
"uno.devserver",
"--mcp-app"
]
},
"UnoDocs": {
"url": "https://mcp.platform.uno/v1"
}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"mcpServers": {
"UnoApp": {
"command": "dotnet",
"args": [
"dnx",
"-y",
"uno.devserver",
"--mcp-app"
]
}
}
}
+127
View File
@@ -0,0 +1,127 @@
# AGENTS.md
Guidance for OpenCode agents working in this repo. Read this before editing manifests.
## What this repo is
Plain Kubernetes manifests (no Helm, no kustomize, no build step) for a homelab
cluster on Hetzner Cloud. Cilium is the CNI/LB; Hetzner CSI (`hcloud-volumes`)
and a SMB CSI (`slow`) provide storage. There is no application source code —
every file is YAML/TXT applied with `kubectl apply -f`.
## Commands
- Apply a manifest: `kubectl apply -f <path>`
- No lint/typecheck/test pipeline exists. Verify changes by applying against the
cluster and checking `kubectl get/describe/logs`.
- Monitoring stack only: install/upgrade via Helm (see `README.md` for exact
commands and the pinned chart version `87.3.0`). Do not re-apply the Grafana
manifests via `kubectl apply` and Helm together — Grafana is hand-managed
(`Monitoring/Grafana/`), Prometheus is Helm-managed.
## Storage — gotchas that bit us
- **`slow` is the default StorageClass** (SMB CSI). `hcloud-volumes` is *not*
default. PVCs that omit `storageClassName` land on SMB, not Hetzner volumes —
set it explicitly when you want Hetzner block storage.
- `local-storage` (`no-provisioner`) requires a matching manual `PersistentVolume`
with `nodeAffinity`; it only binds on the node hosting the PV. Used by the
legacy postgres StatefulSet.
- Only one default StorageClass may exist. If `kubectl get sc` shows two
`(default)`, patch the unwanted one:
`kubectl patch sc <name> -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'`
## Network / IP layout (non-obvious)
- Cilium `LoadBalancerIPPool`s hand out LB IPs from two pools:
- `lan-pool` `10.1.0.101–10.1.0.199` — Cilium ingresses.
- `postgres-pool` `10.2.0.0/24` — dedicated postgres LB, stable IP `10.2.0.122`.
- A LB IP is pinned via annotation `lbipam.cilium.io/ips: <ip>` on the Service,
backed by a matching `CiliumLoadBalancerIPPool`. Keep both in sync or the IP
won't allocate.
- Node IPs have moved (`10.0.2.x` → `10.1.0.x`). Any manifest referencing the
old registry `10.0.2.119:5000` is unreachable from current nodes; use the
public image `pgvector/pgvector:pg18-trixie` instead (see PostgreSQL migration).
- Hetzner Cloud Firewalls (`allow-all-internal`, `allow-all-home`, `Home-ip`)
are applied to every node: inbound only from `10.0.0.0/8` and home
(`192.168.8.0/24`, `192.168.5.0/24`, `78.58.8.250/32`). There are no
outbound rules, so outbound is allow-all. **Adding one outbound rule flips
outbound to deny-all** — if you restrict egress, add the full allowlist in
one call. See `Cluster_admin/firewall.md`.
- IPv6 is egress-only (no inbound IPv6 rules). The `slow` SMB CSI Storage Box
mount uses IPv6 directly; keep it that way.
- Public IPs are kept on workers (Option A). Do not remove Primary IPs or
repoint worker default routes without reading `Cluster_admin/firewall.md`
and the "Firewall / egress" section in `Environment.md`.
- Cluster → home LAN goes through the master's WireGuard (`wg0`). Hetzner's
private network is routed (`/32` per node) and drops non-private sources, so
each worker gets a point-to-point GRE tunnel (`169.254.8.0/24`) to the master;
the master masquerades the traffic to `192.168.5.3` on `wg0`.
`HomeAccess/home_lan_router_daemonset.yaml` keeps the tunnels, routes and NAT
in place, and hardcodes the worker private IPs — update `WORKERS` when nodes
change. The master's `wg0` peer `AllowedIPs` must include `192.168.8.0/24`
(host config). See `HomeAccess/README.md`.
## Secrets are gitignored
`.gitignore` drops `Secrets/` and any `*secret*.yaml`. Secret manifests in the
tree are expected to be created out-of-band and are **not committed**. Do not
`git add` a `*_secret.yaml`/`*_secret.yml`. Read existing secret values from the
cluster with `kubectl get secret` if you need them for a migration step.
## PostgreSQL directory — read the runbook first
`PostgreSQL/MIGRATION_RUNBOOK.md` is the source of truth for the postgres
StatefulSet → `postgres-hetzner` Deployment migration (logical dump/restore,
downtime required, IP repoint `10.0.2.116 → 10.2.0.122`). Do not edit
`PostgreSQL/` manifests without reading it.
Layout:
- `PostgreSQL/Old/` — legacy StatefulSet manifests (`postgress_deplay.yaml`
keeps the original typo'd filename deliberately; used as rollback reference).
- `PostgreSQL/hetzner/` — new Deployment/PVC/Service on `hcloud-volumes`.
- `PostgreSQL/postgres_service.yaml`, `postgres_lb_service.yaml` — the two
Services repointed at `app: postgres-hetzner` after cutover.
## Monitoring directory
- Prometheus is managed by the **kube-prometheus-stack** Helm release; values in
`Monitoring/kube-prometheus-stack.values.yaml`. Bundled Grafana is disabled
(`grafana.enabled: false`); the Grafana in `Monitoring/Grafana/` is
hand-managed and points its datasource at
`prometheus-operated.monitoring.svc.cluster.local:9090`.
- `Monitoring/Prometheus/` is empty — the old hand-rolled Prometheus manifests
were removed when the Helm chart replaced them. Don't recreate them.
- To add a scrape target, create a `ServiceMonitor`/`PodMonitor` CR anywhere;
the Prometheus CR selects all (`serviceMonitorSelector: {}`).
## Docker directory
- `Docker/PostgreSQL/` holds the custom PostgreSQL image build (base
`postgres:18.4` + `pgvector` v0.8.2 built from source, plus rclone/python
helpers). The image is built and pushed by `Docker/PostgreSQL/PostgreSQL_Build.sh`
to the private registry `rg.mariushome.lt/custom-postgres`.
- This is the only build step in the repo; everything else is plain manifests.
Run the shell script from the `Docker/PostgreSQL/` directory so the Docker
build context is correct.
- The registry `rg.mariushome.lt` is the public-facing name for the image
formerly served from `10.0.2.119:5000`. Prefer pulling
`rg.mariushome.lt/custom-postgres` over the legacy `10.0.2.119:5000/...` path
(the latter is unreachable from current nodes — see Network / IP layout).
## Cluster admin notes (operational, not manifests)
- `Cluster_admin/nodes_restart_commands.txt` — drain/reboot/uncordon sequence
per node. Follow that order; node names are real hostnames.
- `Cluster_admin/move _data_example.txt` — one-line `kubectl cp` example (the
leading space in the filename is intentional).
## Editing conventions
- Keep filenames as committed, including typos (`postgress_deplay.yaml`,
`move _data_example.txt`). Other docs and the runbook reference them by name.
- Manifests use `app` label selectors; do not introduce `app.kubernetes.io/*`
labels mid-stream without updating every consumer (Services, ServiceMonitors).
- Prefer editing existing files over creating new ones; new manifests should
follow the per-directory pattern (e.g. `<thing>_deployment.yaml`,
`<thing>_service.yaml`, `<thing>_pvc.yaml`).
+151
View File
@@ -0,0 +1,151 @@
# Hetzner Cloud Firewall — inbound/outbound model
Operational note for the cluster's public network posture ("Option A"):
**public IPs stay, inbound is locked down, outbound is open**. This is not a
manifest — it is managed in the Hetzner Cloud Console / API.
Last verified: **2026-11-26**.
## Servers
| Server | Private IP | Public IPv4 | Public IPv6 |
|---|---|---|---|
| `master-4gb-hel1-2` | `10.1.0.3` | `46.62.205.103` | `2a01:4f9:c013:68e::/64` |
| `ubuntu-4gb-hel1-docker` (Worker-0) | `10.1.0.2` | `65.108.84.87` | `2a01:4f9:c010:e481::/64` |
| `woker-1-8gb-hel1-1` (Woker-1) | `10.1.0.4` | `95.216.198.61` | `2a01:4f9:c013:68ec::/64` |
## Applied firewalls
All three firewalls are applied to **all three** servers.
| Firewall | ID | Inbound | Outbound |
|---|---|---|---|
| `allow-all-internal` | `10660297` | TCP/UDP/GRE/ICMP/ESP from `10.0.0.0/8` | none |
| `allow-all-home` | `10296229` | TCP/UDP/ICMP/GRE/ESP from `192.168.8.0/24`, `192.168.5.0/24` | none |
| `Home-ip` | `10714705` | TCP/UDP from `78.58.8.250/32` (home WAN) | none |
All sources above are IPv4; there are **no IPv6 inbound rules**.
## Effective posture
Hetzner Cloud Firewalls are stateful:
- Inbound `NEW` traffic: **dropped** unless a rule allows it.
- `ESTABLISHED` / `RELATED`: always allowed (responses to outbound connections
come back without an inbound rule).
- Outbound `NEW` traffic: **allowed** as long as there are no outbound rules.
- **Trap:** as soon as *one* outbound rule exists, outbound switches to
deny-by-default and only matching destinations pass. Do not add a single
outbound rule without the complete allowlist.
Consequences:
- The public IPs are **not reachable from the internet**. Verified on
2026-11-25: from the master (a non-home source) ports 22/80/443/6443 on both
worker public IPs were blocked.
- Home LAN/WG (`192.168.8.0/24`, `192.168.5.0/24`, `78.58.8.250`) can reach the
nodes; the private network (`10.0.0.0/8`) can reach them.
- IPv6 is **egress-only**: no inbound IPv6 rules, so nodes can initiate
connections over IPv6 (used by the `slow` SMB Storage Box mount) but nothing
can initiate in.
- Nodes pull images and packages **directly over Hetzner** (Docker Hub, GHCR,
Quay, Ubuntu archive, `rg.mariushome.lt`). No home/VPN dependency.
- `rg.mariushome.lt` resolves to the home WAN (`78.58.8.250`) and is proxied by
the home edge into the cluster; pulls need the `registry-creds` image pull
secret (one per namespace).
- Mailu is **not deployed** (no pods in `mailu`). Its SMTP/IMAP ports are not
open to the internet under this posture. See `Email/README.md` step 3.4 if it
is ever deployed.
## Operating the firewalls
The Hetzner API token is stored in the cluster (CSI token). Do **not** commit
it or paste it into docs/logs:
```bash
TOKEN=$(kubectl -n kube-system get secret hcloud -o jsonpath='{.data.token}' | base64 -d)
```
Inspect firewalls and the rules applied to each server:
```bash
curl -s -H "Authorization: Bearer $TOKEN" \
https://api.hetzner.cloud/v1/firewalls | jq .
curl -s -H "Authorization: Bearer $TOKEN" \
https://api.hetzner.cloud/v1/servers \
| jq -r '.servers[] | "\(.name) firewalls=\([.public_net.firewalls[]?.id] | join(","))"'
```
Replace a firewall's rules (this **replaces all rules** on that firewall, so
include the full inbound + outbound set):
```bash
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' \
https://api.hetzner.cloud/v1/firewalls/10296229/actions/set_rules \
-d @rules.json
```
The Console equivalent is **Firewalls → select firewall → Rules**. Changes are
applied within seconds.
## If outbound must be restricted again
Add the complete allowlist in one `set_rules` call. Starting point (merge these
outbound rules with the current inbound rules, or the inbound rules are lost):
```json
{
"rules": [
{ "direction": "out", "protocol": "tcp", "port": "80", "destination_ips": ["0.0.0.0/0", "::/0"] },
{ "direction": "out", "protocol": "tcp", "port": "443", "destination_ips": ["0.0.0.0/0", "::/0"] },
{ "direction": "out", "protocol": "udp", "port": "53", "destination_ips": ["0.0.0.0/0", "::/0"] },
{ "direction": "out", "protocol": "tcp", "port": "53", "destination_ips": ["0.0.0.0/0", "::/0"] },
{ "direction": "out", "protocol": "udp", "port": "123", "destination_ips": ["0.0.0.0/0", "::/0"] },
{ "direction": "out", "protocol": "tcp", "port": "445", "destination_ips": ["91.98.250.141/32", "2a01:4f8:bacc:2:200::180d/128"] },
{ "direction": "out", "protocol": "udp", "port": "51820", "destination_ips": ["78.58.8.250/32"] },
{ "direction": "out", "protocol": "icmp", "destination_ips": ["0.0.0.0/0", "::/0"] }
]
}
```
Notes:
- `91.98.250.141` / `2a01:4f8:bacc:2:200::180d` are the Hetzner Storage Box
(`//u518679.your-storagebox.de`) used by the `slow` SMB StorageClass.
- `78.58.8.250` is the home WAN / WireGuard endpoint.
- Hetzner's own services (DNS `185.12.64.1/2`, `api.hetzner.cloud`, metadata)
are generally exempt from firewall filtering, but the 443/53 rules cover them.
- Test from a node immediately after: `curl` to a registry, `apt update`, and a
throwaway `crictl pull`.
## Validation checklist
From a node:
```bash
curl -s -o /dev/null -w '%{http_code}\n' https://registry-1.docker.io/v2/ # 401
curl -s -o /dev/null -w '%{http_code}\n' http://archive.ubuntu.com/ubuntu/ # 200
```
From a non-home source (e.g. the master, **not** the home network) the worker
public IPs must refuse:
```bash
nc -vz 95.216.198.61 22 # blocked from master
nc -vz 65.108.84.87 443 # blocked from master
```
Real pull test (per node):
```bash
crictl pull docker.io/library/hello-world:latest
crictl rmi docker.io/library/hello-world:latest
```
## Related
- `Environment.md` → "Firewall / egress"
- `AGENTS.md` → "Network / IP layout"
- `Email/README.md` → step 3.4 (Mailu public SMTP/IMAP caveat)
+113
View File
@@ -0,0 +1,113 @@
# OS package update runbook for Hetzner cluster nodes
Order: **master first, then workers, ONE NODE AT A TIME.**
Verify each node is `Ready` before uncordoning and before moving to the next.
Replace `<node>` with: `master-4gb-hel1-2` | `ubuntu-4gb-hel1-docker` | `woker-1-8gb-hel1-1`
## Per-node sequence
1. From your admin machine: cordon + drain the node so workloads migrate
```bash
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
```
2. Confirm drain finished (pods gone, node marked `SchedulingDisabled`)
```bash
kubectl get nodes
kubectl get pods -A --field-selector spec.nodeName=<node> --watch
```
3. SSH into the node
```bash
ssh <node>
```
4. Inside the node: update OS packages
```bash
sudo apt update && sudo apt upgrade -y
sudo apt autoremove -y
```
5. (Optional) check what needs a reboot; usually kernel/glibc upgrades do
```bash
cat /var/run/reboot-required 2>/dev/null || echo "no reboot required"
```
6. Reboot the node to apply kernel updates
```bash
sudo reboot
```
7. Wait for the node to come back, then from your admin machine verify it's `Ready`
```bash
kubectl get nodes -w
# Wait for: <node> Ready <role> <age> <version>
```
8. Uncordon the node so it accepts pods again
```bash
kubectl uncordon <node>
```
9. Verify workloads re-scheduled and healthy
```bash
kubectl get pods -A --field-selector spec.nodeName=<node>
kubectl get nodes
```
## Full sequence
### master-4gb-hel1-2
```bash
kubectl drain master-4gb-hel1-2 --ignore-daemonsets --delete-emptydir-data
# ssh master-4gb-hel1-2 -> sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y
# sudo reboot
# (wait for Ready)
kubectl uncordon master-4gb-hel1-2
```
### ubuntu-4gb-hel1-docker
```bash
kubectl drain ubuntu-4gb-hel1-docker --ignore-daemonsets --delete-emptydir-data
# ssh ubuntu-4gb-hel1-docker -> sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y
# sudo reboot
# (wait for Ready)
kubectl uncordon ubuntu-4gb-hel1-docker
```
### woker-1-8gb-hel1-1
```bash
kubectl drain woker-1-8gb-hel1-1 --ignore-daemonsets --delete-emptydir-data
# ssh woker-1-8gb-hel1-1 -> sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y
# sudo reboot
# (wait for Ready)
kubectl uncordon woker-1-8gb-hel1-1
```
## Notes
- Do **NOT** upgrade `kubelet`/`kubeadm`/`kubectl` via apt without following the
upstream kubeadm cluster-upgrade procedure first. Pin those packages:
```bash
sudo apt-mark hold kubelet kubeadm kubectl kubernetes-cni
```
Or check the held state with: `apt-mark showhold`
- If a kernel update is **not** in the upgrade set and you want to skip the
reboot, skip step 6 and go straight to uncordon after `apt upgrade`.
- Hetzner CSI/Cilium DaemonSets stay running during drain
(`--ignore-daemonsets`); that's expected and safe.
+22
View File
@@ -0,0 +1,22 @@
# Use the official PostgreSQL image as base
FROM postgres:18.4
# Install build dependencies and pgvector
RUN apt-get update && apt-get install -y \
build-essential \
git \
postgresql-server-dev-18 \
python3 \
python3-pip \
python3-psycopg2 \
rclone \
&& git clone --branch v0.8.4 https://github.com/pgvector/pgvector.git \
&& cd pgvector \
&& make \
&& make install \
&& cd .. \
&& rm -rf pgvector \
&& apt-get remove -y build-essential git postgresql-server-dev-18 \
&& apt-get autoremove -y \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
docker build -t custom-postgres .
docker tag custom-postgres rg.mariushome.lt/custom-postgres
docker push rg.mariushome.lt/custom-postgres
@@ -24,10 +24,25 @@ spec:
value: /var/lib/registry
- name: REGISTRY_HTTP_RELATIVEURLS
value: "true"
- name: REGISTRY_AUTH
value: htpasswd
- name: REGISTRY_AUTH_HTPASSWD_REALM
value: "registry.mariushome.lt"
- name: REGISTRY_AUTH_HTPASSWD_PATH
value: /auth/htpasswd
volumeMounts:
- name: registry-storage
mountPath: /var/lib/registry
- name: registry-htpasswd
mountPath: /auth
readOnly: true
volumes:
- name: registry-storage
persistentVolumeClaim:
claimName: registry-pvc
- name: registry-htpasswd
secret:
secretName: registry-htpasswd
items:
- key: htpasswd
path: htpasswd
+186
View File
@@ -0,0 +1,186 @@
# Email / Mailu
Mailu mail server deployed via the official Helm chart (`mailu 2.7.1`,
appVersion `2024.06.51`). Managed by Helm, **not** `kubectl apply` — same model
as the kube-prometheus-stack release in `Monitoring/`.
## Layout
| File | Kind | How to apply |
|---|---|---|
| `mailu_namespace.yaml` | Namespace | `kubectl apply -f` |
| `mailu_lbippool.yaml` | CiliumLoadBalancerIPPool (`10.4.0.0/24`) | `kubectl apply -f` |
| `mailu.values.yaml` | Helm values | `helm upgrade ... -f` (do NOT `kubectl apply`) |
Two non-Helm manifests (namespace + LBIP pool) are applied once with
`kubectl apply -f`. Everything else is rendered by the Helm chart.
## Prerequisites — do these first (in order)
### 1. Apply the namespace + Cilium LB pool
```bash
kubectl apply -f Email/mailu_namespace.yaml
kubectl apply -f Email/mailu_lbippool.yaml
```
### 2. Create the Mailu databases on the existing PostgreSQL
Mailu reuses the existing `postgres-hetzner` instance in the `database`
namespace (`Service postgres.database.svc.cluster.local:5432`, admin user
`admin`). The chart does NOT create databases/users when `externalDatabase` is
enabled, so do it manually before `helm install`.
Get a shell on the postgres pod and create the `mailu` + `roundcube` databases
and users. Replace `<MAILU_PW>` and `<ROUNDCUBE_PW>` with strong generated
values (you'll reuse them in the secret below).
```bash
# Generate the two passwords once and keep them for the next step:
MAILU_PW=$(pwgen 24 1); echo "mailu: $MAILU_PW"
ROUNDCUBE_PW=$(pwgen 24 1); echo "roundcube: $ROUNDCUBE_PW"
# Create databases + users on the existing postgres-hetzner:
kubectl exec -n database deploy/postgres-hetzner -- psql -U admin -d postgres <<SQL
CREATE USER mailu WITH LOGIN PASSWORD '$MAILU_PW';
CREATE USER roundcube WITH LOGIN PASSWORD '$ROUNDCUBE_PW';
CREATE DATABASE mailu OWNER mailu;
CREATE DATABASE roundcube OWNER roundcube;
\c mailu
CREATE EXTENSION IF NOT EXISTS citext;
SQL
```
`citext` is required by Mailu on the `mailu` database (case-insensitive text).
The `roundcube` database needs no extension.
### 3. Create the out-of-band secrets (gitignored — never `git add`)
Following the repo convention (see root README "Private registry authentication"
and AGENTS.md "Secrets are gitignored"), these are created manually and are NOT
committed.
```bash
# Mailu secret-key + initial admin password
kubectl create secret generic mailu-secret -n mailu \
--from-literal=secret-key="$(pwgen 16 1)" \
--from-literal=initial-admin-password="$(pwgen 24 1)"
# Mailu + Roundcube DB credentials against the existing postgres-hetzner.
# Reuse the exact MAILU_PW / ROUNDCUBE_PW from step 2.
kubectl create secret generic mailu-db-secret -n mailu \
--from-literal=database=mailu \
--from-literal=username=mailu \
--from-literal=password="$MAILU_PW" \
--from-literal=roundcube-password="$ROUNDCUBE_PW"
```
If `pwgen` is not installed: `apt-get install -y pwgen` (or use
`openssl rand -base64 24`).
### 3. External (non-repo) prerequisites — you must do these outside k8s
1. **Hetzner PTR record.** In the Hetzner Cloud Console, set the reverse DNS of
the LoadBalancer IP `10.4.0.122` to `mail.mariushome.lt`. Without a PTR,
receivers (Gmail/Outlook) silently drop your mail.
2. **DNS records at your DNS provider** (NOT in this repo):
- `A mail.mariushome.lt -> <public IP that 10.4.0.122 routes to>`
- `MX mariushome.lt -> mail.mariushome.lt (prio 10)`
- `TXT mariushome.lt "v=spf1 mx ~all"`
- `TXT _dmarc.mariushome.lt "v=DMARC1; p=quarantine; rua=mailto:postmaster@mariushome.lt"`
- DKIM: generated by the Mailu admin UI on first boot — add the `TXT`
record Mailu shows you (typically `mail._domainkey.mariushome.lt`).
- Optional: MTA-STS (`TXT _mta-sts.mariushome.lt` + a `/.well-known/mta-sts.txt`
served over HTTPS — chart supports it via `front.overrides`).
3. **Cloudflare**: only the web UIs (`mail.mariushome.lt`, and the `/admin` +
`/webmail` paths) are proxied through Cloudflare (orange cloud). The SMTP /
IMAP / Submission / ManageSieve ports must **NOT** go through Cloudflare —
they need a direct, DNS-only route (grey cloud) to the Hetzner-announced IP.
Mail clients should be configured against `mail.mariushome.lt` directly.
4. **Hetzner Cloud firewall**: the current firewalls only allow inbound from
the private network and home (`allow-all-internal`, `allow-all-home`,
`Home-ip`). There are **no** public inbound rules for 25/465/587/143/993/
4190, so Mailu is not reachable directly from the internet as-is. To expose
it, add explicit inbound TCP rules for those ports (this reopens the public
IPs for those ports) while keeping the private/home rules. See
`Cluster_admin/firewall.md`. Mailu is not currently deployed (no pods in
`mailu`), so this is preparatory. Outbound is allow-all now, but Hetzner
may still block outbound 25 for new accounts — confirm before relying on
direct delivery.
## Install / upgrade
```bash
# One time:
helm repo add mailu https://mailu.github.io/helm-charts
helm repo update
# Install:
helm install mailu mailu/mailu -n mailu --version 2.7.1 -f Email/mailu.values.yaml
# Upgrade after editing Email/mailu.values.yaml:
helm repo update
helm upgrade mailu mailu/mailu -n mailu --version 2.7.1 -f Email/mailu.values.yaml
```
The chart version `2.7.1` and `mailuVersion: "2024.06"` in the values are
pinned deliberately — a mail server should move conservatively. To bump, edit
both the `--version` here and (if needed) `mailuVersion` in the values, then
test against a non-production domain first.
## Verification after install
```bash
helm status mailu -n mailu
kubectl get pods -n mailu # front, admin, imap, smtp, antispam, webmail, redis
kubectl get svc -n mailu
kubectl get ingress -n mailu
kubectl get pvc -n mailu # mail storage (10Gi) only; DB lives on existing postgres-hetzner
kubectl get ciliumloadbalancerippool mailu-pool
# Confirm the pinned mail LB IP allocated to the front external Service:
kubectl get svc -n mailu -l app.kubernetes.io/component=front \
-o jsonpath='{range .items[*]}{.metadata.name}{" "}{.status.loadBalancer.ingress}{"\n"}{end}'
# Expect 10.4.0.122 in the ingress list.
# Mail flow smoke test (from inside the cluster):
kubectl exec -n mailu deploy/mailu-smtp -- swaks --to <external-address> \
--from admin@mariushome.lt --server mail.mariushome.lt
# DNS sanity (run from outside the cluster):
dig MX mariushome.lt
dig -x <mail-LB-public-IP> # must return mail.mariushome.lt (PTR)
```
## Notes / gotchas
- **`slow` is the default StorageClass** in this cluster (SMB). The mail PVC
in `mailu.values.yaml` sets `storageClassName: hcloud-volumes` explicitly —
do not remove it, or mail data lands on SMB. (The metadata DB now lives on
the existing `postgres-hetzner`, whose PVC already uses `hcloud-volumes`.)
- **Only one default StorageClass may exist.** If `kubectl get sc` ever shows
two `(default)`, patch the unwanted one (see AGENTS.md).
- Mailu reuses the existing `postgres-hetzner` instance (`database` namespace)
via `externalDatabase`. The chart's bundled PostgreSQL subchart is disabled
(`postgresql.enabled: false`). The `mailu` and `roundcube` databases/users
must be created manually before `helm install` — see step 2 above. The
custom-postgres image's pgvector extension is irrelevant to Mailu; it works
fine against the existing server.
- `L2AnnouncementPolicy` (`Cilium/L2AnnouncementPolicy.yaml`) already announces
LoadBalancer IPs, so no new policy is needed for `10.4.0.122`.
- The `front` chart subchart defaults to `hostPort: true` (assumes bare-metal
nodes). This deployment disables `hostPort` and uses `externalService`
instead, so the Cilium LBIPAM pool hands out the IP. Do not re-enable
`hostPort` on a managed k8s cluster.
- `ingress.realIpFrom` lists the Cloudflare CIDRs; if you ever switch the
upstream proxy, update this list or `front` will rate-limit / ban the new
proxy IPs (Mailu docs warn about this).
- Roundcube's DB lives in the existing `postgres-hetzner` instance. The chart
does NOT auto-create it for `externalDatabase` mode — step 2 above handles
it manually.
- `kubectl apply -f` does NOT apply to `mailu.values.yaml` — it is consumed
only by `helm`. Applying it with kubectl does nothing useful and may
confuse diff tooling.
- Admin UI is at `https://mail.mariushome.lt/admin`, webmail at
`https://mail.mariushome.lt/webmail` (default paths; configurable via
`admin.uri` / webmail settings in the chart).
+117
View File
@@ -0,0 +1,117 @@
# Mailu Helm values — managed via Helm (NOT kubectl apply)
# Chart: mailu 2.7.1 (appVersion 2024.06.51)
# Install/upgrade commands in Email/README.md
# Edit here, then: helm upgrade mailu mailu/mailu -n mailu --version 2.7.1 -f Email/mailu.values.yaml
# -----------------------------
# Identity
# -----------------------------
hostnames:
- mail.mariushome.lt # primary mail hostname (PTR target)
domain: mariushome.lt
timezone: Europe/Vilnius
logLevel: INFO
postmaster: postmaster
# -----------------------------
# Secrets (out-of-band, see README.md)
# -----------------------------
existingSecret: mailu-secret # holds secret-key + initial-admin-password
initialAccount:
enabled: true
username: admin
domain: mariushome.lt
existingSecret: mailu-secret
existingSecretPasswordKey: initial-admin-password
mode: ifmissing
# -----------------------------
# Mail storage — single PVC on Hetzner block storage
# hcloud-volumes is NOT the default SC (slow/SMB is) — set explicitly per AGENTS.md
# -----------------------------
persistence:
single_pvc: true
storageClass: hcloud-volumes
size: 10Gi
accessModes: [ReadWriteOnce]
# -----------------------------
# External PostgreSQL — reuse the existing postgres-hetzner instance
# (database namespace, Service postgres.database.svc.cluster.local:5432)
# The mailu + roundcube databases and users must be created manually first;
# see Email/README.md "Create the Mailu databases on the existing PostgreSQL".
# -----------------------------
postgresql:
enabled: false # do NOT deploy the bundled postgres subchart
externalDatabase:
enabled: true
type: postgresql
host: postgres.database.svc.cluster.local
port: 5432
existingSecret: mailu-db-secret # keys: database, username, password, roundcube-password
existingSecretDatabaseKey: database
existingSecretUsernameKey: username
existingSecretPasswordKey: password
# Roundcube DB lives in the same external PG; chart does NOT create it for
# externalDatabase mode — must be created manually (see README.md).
global:
database:
roundcube:
database: roundcube
username: roundcube
existingSecret: mailu-db-secret
existingSecretPasswordKey: roundcube-password
# -----------------------------
# Web UIs (admin + webmail) — behind Cilium Ingress
# Upstream Cloudflare terminates TLS; no cert-manager in this repo
# -----------------------------
ingress:
enabled: true
ingressClassName: cilium
pathType: Prefix
annotations:
ingress.cilium.io/loadbalancer-mode: "dedicated" # matches gitea/immich pattern
tls: false # Cloudflare terminates TLS upstream
selfSigned: false
realIpHeader: CF-Connecting-IP
# Cloudflare CIDRs — must be trusted or front will rate-limit/ban CF edge IPs
# Source: https://www.cloudflare.com/ips/ (re-check periodically)
realIpFrom: >-
103.21.244.0/22,103.22.200.0/22,103.31.4.0/22,104.16.0.0/13,104.24.0.0/14,
108.162.192.0/18,131.0.72.0/22,141.101.64.0/18,162.158.0.0/15,172.64.0.0/13,
173.245.48.0/20,188.114.96.0/20,190.93.240.0/20,197.234.240.0/22,198.41.128.0/17,
2400:cb00::/32,2606:4700::/32,2803:f800::/32,2405:b500::/32,2405:8100::/32,
2a06:98c0::/29,2c0f:f248::/32
# -----------------------------
# Mail ports (SMTP/IMAP/Submission/ManageSieve) — Cilium LoadBalancer
# NOT hostPort (chart default assumes bare-metal); NOT through Cloudflare
# IP pinned via lbipam.cilium.io/ips to 10.4.0.122 (mailu-pool, see mailu_lbippool.yaml)
# -----------------------------
front:
hostPort:
enabled: false # chart default true — must disable for k8s LB
externalService:
enabled: true
type: LoadBalancer
externalTrafficPolicy: Local
annotations:
lbipam.cilium.io/ips: "10.4.0.122"
ports:
smtp: true
smtps: true
submission: true
imap: true
imaps: true
pop3: false # POP3 disabled per requirement
pop3s: false
manageSieve: true
# -----------------------------
# Mailu app version pin (stable line)
# -----------------------------
mailuVersion: "2024.06"
+8
View File
@@ -0,0 +1,8 @@
apiVersion: "cilium.io/v2"
kind: CiliumLoadBalancerIPPool
metadata:
name: "mailu-pool"
spec:
blocks:
- start: "10.4.0.0"
stop: "10.4.0.255"
+4
View File
@@ -0,0 +1,4 @@
apiVersion: v1
kind: Namespace
metadata:
name: mailu
+198
View File
@@ -0,0 +1,198 @@
# Environment Description
Reference for other agents/automata working on this repo. Describes the
homelab Kubernetes cluster's shape, conventions and gotchas. No secrets or
credentials are included — see `Secrets` section below for how they are handled.
## Repository
**Type:** Plain Kubernetes manifests (no Helm/kustomize/build for the majority
of the tree; two exceptions managed by Helm). Applied directly with
`kubectl apply -f <path>`. No CI/lint/test pipeline — verify by applying and
inspecting `kubectl get/describe/logs`.
**Platform:** Homelab cluster on Hetzner Cloud.
**Repo root layout:**
| Directory | Purpose |
|-------------------|----------------------------------------------------------------------|
| `Cilium/` | Cilium networking: `LoadBalancerIPPool`, `L2AnnouncementPolicy`, ingress example |
| `Cluster_admin/` | Operational notes (node reboot/update sequences, firewall/egress, `kubectl cp` example) — not manifests applied to cluster |
| `Docker/PostgreSQL/` | Custom PostgreSQL image build (Dockerfile + build script) |
| `DockerRegistry/` | Private Docker registry Deployment + Service + PVC, and a registry UI subdirectory |
| `Email/` | Mailu mail server (Helm) + namespace + Cilium LB pool manifests |
| `Gitea/` | Gitea Deployment/Service/Ingress/Namespace/PVC/DB-secret |
| `HomeAccess/` | DaemonSet that routes `192.168.8.0/24` (home LAN) through the master's WireGuard + README |
| `Immich/` | Immich server + machine-learning + redis Deployments/Services, config + secret |
| `Monitoring/` | kube-prometheus-stack Helm values + hand-managed Grafana manifests |
| `PostgreSQL/` | PostgreSQL manifests (only `hetzner/` subdir currently present) |
| `Secrets/` | Docker registry login credentials (gitignored — not committed) |
| `volume/` | PVC and SMB volume examples |
## Cluster Infrastructure
- **CNI/LB:** Cilium. Provides pod networking and Layer 2-announced
LoadBalancer IPs via `CiliumLoadBalancerIPPool` + `CiliumL2AnnouncementPolicy`.
- **L2 Announcement:** `l2-policy` in `Cilium/L2AnnouncementPolicy.yaml` —
announces `externalIPs` and `loadBalancerIPs` on nodes that are **not**
control-plane (`node-role.kubernetes.io/control-plane` `DoesNotExist`).
- **LoadBalancer IP Pools** (`CiliumLoadBalancerIPPool`):
| Pool | Range | File | Purpose |
|--------------|---------------------|-------------------------------|-------------------------------------------|
| `lan-pool` | `10.1.0.101–10.1.0.199` | `Cilium/LoadBalancerIPPool.yaml` | General Cilium ingresses / services |
| `mailu-pool` | `10.4.0.0–10.4.0.255` | `Email/mailu_lbippool.yaml` | Mailu mail LB (SMTP/IMAP/Submission) |
- **LB IP pinning:** Annotation `lbipam.cilium.io/ips: <ip>` on a `Service`,
backed by a matching pool. Example: Mailu front service pins `10.4.0.122`
(see `Email/mailu.values.yaml`).
- **Ingress class:** `cilium`. Ingresses use
`ingress.cilium.io/loadbalancer-mode: "dedicated"`.
## Network / IP Layout
- **Node IPs:** `10.1.0.x` (previously `10.0.2.x` — old addresses are
unreachable from current nodes).
- Any manifest referencing the old registry `10.0.2.119:5000` is stale; use
the public image name `rg.mariushome.lt/custom-postgres` instead.
- LB pool ranges are RFC1918 and announced via L2 on worker nodes.
### Firewall / egress
Public IPs are kept on all nodes (Option A). Hetzner Cloud Firewalls are
applied to every node:
- `allow-all-internal` — inbound from `10.0.0.0/8`
- `allow-all-home` — inbound from `192.168.8.0/24`, `192.168.5.0/24`
- `Home-ip` — inbound from `78.58.8.250/32` (home WAN)
There are **no outbound rules**, so Hetzner allows all outbound. Inbound `NEW`
from the internet is dropped; IPv6 has no inbound rules and is egress-only.
Nodes pull images/packages directly over Hetzner, and the `slow` SMB Storage Box
stays on direct IPv6.
**Gotcha:** adding a single outbound rule flips Hetzner outbound to
deny-by-default. Add the complete allowlist in one call, or leave outbound open.
See `Cluster_admin/firewall.md` for the rules, API commands and validation.
The master's WireGuard (`wg0`, `192.168.5.0/24`) is the only path between the
cluster and the home LAN; it is **not** an internet path. It carries both
directions: home → cluster (kubectl, LB IPs) and cluster → home (`HomeAccess/`:
each worker gets a point-to-point GRE tunnel to the master because Hetzner's
private network is routed and drops non-private sources, and the master
masquerades the traffic to `192.168.5.3`). The private-only-worker design
remains deferred: the home router does not forward the WG subnet, so home
devices reach workers only through the master. Mailu is not deployed and its
SMTP/IMAP ports are not open to the internet.
## Storage
Three `StorageClass`es exist:
| StorageClass | Driver | Default? | Notes |
|------------------|------------------|----------|-----------------------------------------------------------------------|
| `slow` | SMB CSI | **Yes** | PVCs that omit `storageClassName` land here (SMB share). |
| `hcloud-volumes` | Hetzner CSI | No | Block storage; set `storageClassName: hcloud-volumes` explicitly. |
| `local-storage` | `no-provisioner` | No | Requires a matching manual `PersistentVolume` with `nodeAffinity`. |
Gotchas:
- `slow` (SMB) is the **default**; `hcloud-volumes` is not. Omitting
`storageClassName` puts a PVC on SMB. When block storage is wanted, set it
explicitly.
- Only one default StorageClass may exist. If `kubectl get sc` shows two
`(default)`, patch the unwanted one:
`kubectl patch sc <name> -p '{"metadata":{"annotations":{"storageclass.kubernetes.io/is-default-class":"false"}}}'`
- Examples of both PVC and SMB volume usage live in `volume/`.
## Workloads
| Directory | Workload(s) | Namespace | Image / Notes |
|-----------------------|-----------------------------------------------------|--------------|-----------------------------------------------------------------------------------------------------|
| `PostgreSQL/hetzner/` | `postgres-hetzner` Deployment + ClusterIP Service + PVC + ConfigMap | `database` | `rg.mariushome.lt/custom-postgres` (custom image, see Build below). PVC on `hcloud-volumes`. Creds via `postgres-secret`. `app: postgres-hetzner` selector. Recreate strategy. |
| `Gitea/` | Gitea Deployment + Service + Ingress + Namespace + PVC | `gitea` | `docker.io/gitea/gitea:latest`. Uses external Postgres at `postgres.database.svc.cluster.local:5432`, DB `gitea`, user `admin`, pwd from `gitea-db-secret`. Ingress host `git.mariushome.lt`. PVC `gitea-hetzner-pvc`. |
| `Immich/` | Immich server + machine-learning + redis Deployments/Services + config + secret | `immich` | `ghcr.io/immich-app/immich-server:v3`; ML image separate. Init container waits on `postgres.database.svc.cluster.local:5432`. Uses `immich-env` ConfigMap + `immich-db-secret`. Library PVC `immich-lib`. |
| `DockerRegistry/` | Registry Deployment + Service + PVC + UI (Deployment/Service/Ingress) | `registry` | `registry:2`. htpasswd auth mounted from `registry-htpasswd` Secret. PVC `registry-pvc`. |
| `Email/` | Mailu (Helm release) | `mailu` | Helm chart `mailu` v2.7.1 (appVersion `2024.06.51`). Domain `mariushome.lt`. Reuses external `postgres-hetzner`; bundled postgres subchart disabled. Mail LB pinned to `10.4.0.122`. TLS terminated upstream by Cloudflare. |
| `Monitoring/Grafana/` | Hand-managed Grafana Deployment + Service + Ingress + PVC + datasource + DB/app secrets | `monitoring` | `docker.io/grafana/grafana:latest`. Datasource points at `prometheus-operated.monitoring.svc.cluster.local:9090`. |
Postgres is the shared database backend: Gitea, Immich, and Mailu all connect
to the same `postgres-hetzner` instance via the `postgres` Service in the
`database` namespace (`postgres.database.svc.cluster.local:5432`).
## Monitoring Stack
- **kube-prometheus-stack** Helm release (namespace `monitoring`), chart
version pinned `87.3.0`. Values in `Monitoring/kube-prometheus-stack.values.yaml`.
- Prometheus: 15d retention, `10Gi` PVC on `hcloud-volumes`, selects all
ServiceMonitors/PodMonitors/Rules/Probes (`{}SelectorNilUsesHelmValues: false`).
- Alertmanager: **disabled**.
- Bundled Grafana: **disabled** (`grafana.enabled: false`) — a hand-managed
Grafana lives in `Monitoring/Grafana/`.
- Node Exporter + kube-state-metrics: enabled via chart subcharts.
- `Monitoring/Prometheus/` is empty — the previous hand-rolled Prometheus
manifests were removed when the Helm chart replaced them. Do not recreate.
- To add a scrape target, create a `ServiceMonitor`/`PodMonitor` CR anywhere;
the Prometheus CR selects all of them.
- Install/upgrade commands are in `README.md`. Do not re-apply Grafana via both
`kubectl apply` and Helm — Grafana is hand-managed, Prometheus is Helm-managed.
## Container Image Build
- `Docker/PostgreSQL/` holds the custom PostgreSQL image: base `postgres:18.4`
+ `pgvector` v0.8.2 built from source, plus rclone/python helpers.
- Build/push handled by `Docker/PostgreSQL/PostgreSQL_Build.sh`, which pushes to
`rg.mariushome.lt/custom-postgres`. Run the script from the
`Docker/PostgreSQL/` directory so the Docker build context is correct.
- `rg.mariushome.lt` is the public-facing name for the registry formerly served
from `10.0.2.119:5000`; the old path is unreachable from current nodes.
## Secrets — handling (values are NOT shared here)
- `Secrets/` and any `*secret*.yaml`/`*secret*.yml` are gitignored; secret
manifests are created out-of-band and are **not committed**. Do not
`git add` a secret manifest.
- Secret objects consumed by workloads (names only, values held out-of-band):
- `database/postgres-secret` — PostgreSQL credentials.
- `gitea/gitea-db-secret` — Gitea DB password.
- `immich/immich-db-secret` — Immich DB credentials.
- `registry/registry-htpasswd` — htpasswd file for the private registry.
- `mailu/mailu-secret` + `mailu/mailu-db-secret` — Mailu app + DB secrets.
- `monitoring/grafana-secret` + `monitoring/grafana-db-secret` — Grafana app + DB secrets.
- `registry-creds` imagePullSecret (one per namespace pulling from
`rg.mariushome.lt`, e.g. `database`) is required for workloads referencing
the private registry. Created out-of-band via
`kubectl create secret docker-registry registry-creds ...`.
- Read existing secret values from the cluster with `kubectl get secret` if a
migration step needs them.
## Conventions
- Manifests use `app` label selectors; do not introduce
`app.kubernetes.io/*` labels mid-stream without updating every consumer
(Services, ServiceMonitors).
- Per-resource file naming pattern: `<thing>_deployment.yaml`,
`<thing>_service.yaml`, `<thing>_pvc.yaml`.
- Filenames are kept verbatim, including intentional typos and oddities
(`move _data_example.txt` has a leading space). Other docs reference these
names directly.
- Helm-managed pieces (kube-prometheus-stack, Mailu) are upgraded via
`helm upgrade ... -f <values.yaml>`, **not** `kubectl apply` for the values
file. Their accompanying Namespace/LBIPPool manifests are still applied with
`kubectl apply`.
## Cluster Admin (operational, not manifests)
- `Cluster_admin/nodes_restart_commands.txt` — drain/reboot/uncordon sequence
per node. Follow that order.
- `Cluster_admin/nodes_update_commands.md` — node update procedure.
- `Cluster_admin/move _data_example.txt` — `kubectl cp` example (leading space
in the filename is intentional).
## Quick Reference — Commands
- Apply a manifest: `kubectl apply -f <path>`
- Apply Mailu non-Helm pieces: `kubectl apply -f Email/mailu_namespace.yaml`
and `kubectl apply -f Email/mailu_lbippool.yaml`
- Upgrade Mailu: `helm upgrade mailu mailu/mailu -n mailu --version 2.7.1 -f Email/mailu.values.yaml`
- Upgrade monitoring: see `README.md` (kube-prometheus-stack, version `87.3.0`)
+129
View File
@@ -0,0 +1,129 @@
# Home access from the cluster
Lets pods and nodes reach the home LAN at `192.168.8.0/24` (the `pop-os`
workstation lives there) through the master's existing WireGuard tunnel.
```
pod on worker --Cilium--> worker node
| SNAT to 169.254.8.X, GRE (outer 10.1.0.X -> 10.1.0.3)
v
master 10.1.0.3
| forward + MASQUERADE out wg0 (src 192.168.5.3)
v
home router --> 192.168.8.28
```
Two things make this less obvious than it looks:
1. **Hetzner's private network is routed, not L2.** Each node has a `/32`
(`10.1.0.x/32`) with a gateway at `10.1.0.1`; you cannot ARP a peer and use
it as a next hop.
2. **It drops non-private sources.** A packet forwarded by the master with
`source 192.168.8.x` never reaches the worker's NIC, so the return path has
to be tunnelled as well.
Hence the point-to-point GRE tunnels (`169.254.8.0/24`) between each worker and
the master. The inner packet keeps its real source end to end; only the outer
header uses the private node IPs. The master then masquerades `169.254.8.0/24`
to `192.168.5.3` on `wg0`, the address the PC already answers.
| Worker private IP | Tunnel pair |
|---|---|
| `10.1.0.2` | `169.254.8.0/31` (worker `.0`, master `.1`) |
| `10.1.0.4` | `169.254.8.4/31` (worker `.4`, master `.5`) |
The worker list is hardcoded in the DaemonSet (`WORKERS`). Update it when a node
is added, removed or renumbered.
## Prerequisites (host-side, not managed here)
1. On `master-4gb-hel1-2`, the `/etc/wireguard/wg0.conf` peer for the home
router must list the home LAN:
```ini
AllowedIPs = 192.168.5.0/24, 192.168.8.0/24
```
Reload with `wg syncconf wg0 <(wg-quick strip wg0)` **and** add the route if
`ip route get 192.168.8.28` does not say `dev wg0` (`wg syncconf` does not
install routes):
```bash
ip route replace 192.168.8.0/24 dev wg0
ip route get 192.168.8.28 # expect: dev wg0 src 192.168.5.3
```
2. The home router routes `192.168.8.0/24` into the WireGuard tunnel and
allows WireGuard ↔ LAN forwarding.
3. Hetzner Cloud Firewall `allow-all-home` includes `192.168.8.0/24`.
## Deploy
```bash
kubectl apply -f HomeAccess/home_lan_router_daemonset.yaml
kubectl -n kube-system rollout status ds/home-lan-router
```
The DaemonSet is privileged with `hostNetwork: true` because it programs the
node's interfaces, routes and iptables. A 60 s reconcile loop re-applies
everything, so reboots, drains, Cilium upgrades and iptables flushes heal
themselves.
## Verify
```bash
# master: tunnels, NAT
kubectl -n kube-system exec ds/home-lan-router -- ip -br addr show | grep home-gw
kubectl -n kube-system exec ds/home-lan-router -- iptables -t nat -S POSTROUTING | grep 192.168.8
# worker: tunnel + route
kubectl -n kube-system exec <worker-pod> -- ip route show 192.168.8.0/24
# end-to-end (ICMP is the quickest; use any listening TCP port on the PC)
kubectl -n kube-system exec <worker-pod> -- ping -c2 192.168.8.28
kubectl -n kube-system exec <worker-pod> -- nc -vz -w2 192.168.8.28 22
kubectl -n gitea exec deploy/gitea -- curl -s -o /dev/null -w '%{http_code}\n' -m 5 http://192.168.8.28:<port-on-the-pc>/
```
`<port-on-the-pc>` needs an HTTP listener; when nothing is running on `pop-os`,
the ICMP and `nc` checks are enough.
## Notes
- Only `192.168.8.0/24` becomes reachable from pods, not the rest of the home
network.
- `pop-os` gets its address over DHCP. The route is subnet-wide, so a lease
change does not break routing; add a DHCP reservation on the UniFi gateway if
anything references the address.
- The worker `rp_filter` must be permissive (`0`) on the GRE interfaces and the
master's `all.rp_filter` must be `0`; the DaemonSet sets both. This is what
lets the forwarded, un-NAT'd reply enter the stack.
- TCP MSS is clamped to `1356` (`1396` GRE inner MTU − 40) on the workers, so
payloads do not black-hole on PMTUD.
- The host and the containers both use the `nf_tables` iptables backend, so
rules are visible and editable from either side.
## Rollback
```bash
kubectl delete -f HomeAccess/home_lan_router_daemonset.yaml
```
Host state (interfaces, routes, iptables rules) survives pod deletion; remove it
manually or reboot the nodes:
```bash
# workers
ip tunnel del home-gw
iptables -t nat -D CILIUM_POST_nat -d 192.168.8.0/24 -j RETURN
iptables -t nat -D POSTROUTING -s 10.0.0.0/8 -d 192.168.8.0/24 -j SNAT --to-source 169.254.8.X
iptables -D FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# master
ip tunnel del home-gw-0 home-gw-4
iptables -t nat -D POSTROUTING -s 169.254.8.0/24 -d 192.168.8.0/24 -o wg0 -j MASQUERADE
iptables -t nat -D POSTROUTING -s 10.0.0.0/8 -d 192.168.8.0/24 -o wg0 -j MASQUERADE
iptables -D FORWARD -i 'home-gw+' -o wg0 -j ACCEPT
iptables -D FORWARD -i wg0 -o 'home-gw+' -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
```
+149
View File
@@ -0,0 +1,149 @@
# Gives the cluster a route to the home LAN (192.168.8.0/24) through the
# master's WireGuard tunnel (wg0) and SNATs it to the master's WG address, so
# replies come back over the path the home router already knows.
#
# Hetzner's private network is routed (/32 per node) and drops packets whose
# source is not a private address, so worker traffic cannot simply be routed
# "via 10.1.0.3". Instead each worker gets a point-to-point GRE tunnel to the
# master: the inner packet keeps its real source, the outer packet uses the
# private node IPs.
#
# Prerequisite (host-side, see README.md): the master's wg0 peer must list
# 192.168.8.0/24 in AllowedIPs.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: home-lan-router
namespace: kube-system
labels:
app: home-lan-router
spec:
selector:
matchLabels:
app: home-lan-router
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 10%
template:
metadata:
labels:
app: home-lan-router
spec:
hostNetwork: true
dnsPolicy: ClusterFirstWithHostNet
priorityClassName: system-node-critical
tolerations:
- operator: Exists
containers:
- name: router
image: nicolaka/netshoot:v0.13
command: ["/bin/bash", "-c"]
args:
- |
set -u
HOME_LAN="192.168.8.0/24"
MASTER_IP="10.1.0.3"
WG_IF="wg0"
TUN_NET="169.254.8.0/24"
TUN_MTU=1396
MSS=1356
# Worker private IPs. Update this list when a node is added,
# removed or renumbered. The master ignores its own address.
WORKERS="10.1.0.2 10.1.0.4"
is_master() {
# The label is empty on workers; wg0 is a fallback in case the
# label lookup comes back empty on the master.
[ -n "${CONTROL_PLANE:-}" ] || ip link show "$WG_IF" >/dev/null 2>&1
}
# /31 pair for a worker, derived from the last octet of its IP:
# 10.1.0.2 -> 169.254.8.0/31, 10.1.0.4 -> 169.254.8.4/31.
tun_net() { echo $(( ($1 - 2) * 2 )); }
master_loop() {
for w in $WORKERS; do
local last dev net
last="${w##*.}"
net="$(tun_net "$last")"
dev="home-gw-$net"
if ! ip link show "$dev" >/dev/null 2>&1; then
ip tunnel add "$dev" mode gre local "$MASTER_IP" remote "$w" ttl 255
fi
ip link set "$dev" mtu "$TUN_MTU" up
ip addr replace "169.254.8.$((net + 1))/31" dev "$dev"
ip route replace "169.254.8.$net/31" dev "$dev"
sysctl -qw "net.ipv4.conf.$dev.rp_filter=0" || true
done
sysctl -qw net.ipv4.conf.all.rp_filter=0 || true
sysctl -qw net.ipv4.ip_forward=1 || true
for src in "$TUN_NET" "10.0.0.0/8"; do
iptables -t nat -C POSTROUTING -s "$src" -d "$HOME_LAN" -o "$WG_IF" -j MASQUERADE 2>/dev/null \
|| iptables -t nat -A POSTROUTING -s "$src" -d "$HOME_LAN" -o "$WG_IF" -j MASQUERADE
done
iptables -C FORWARD -i 'home-gw+' -o "$WG_IF" -j ACCEPT 2>/dev/null \
|| iptables -I FORWARD 1 -i 'home-gw+' -o "$WG_IF" -j ACCEPT
iptables -C FORWARD -i "$WG_IF" -o 'home-gw+' -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \
|| iptables -I FORWARD 1 -i "$WG_IF" -o 'home-gw+' -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
}
worker_loop() {
local local_ip last net dev
local_ip="$(ip route get "$MASTER_IP" | sed -n 's/.* src \([^ ]*\).*/\1/p')"
[ -n "$local_ip" ] || { echo "ERROR: cannot determine local IP"; return 1; }
last="${local_ip##*.}"
net="$(tun_net "$last")"
dev="home-gw"
if ! ip link show "$dev" >/dev/null 2>&1; then
ip tunnel add "$dev" mode gre local "$local_ip" remote "$MASTER_IP" ttl 255
fi
ip link set "$dev" mtu "$TUN_MTU" up
ip addr replace "169.254.8.$net/31" dev "$dev"
ip route replace "$HOME_LAN" via "169.254.8.$((net + 1))" dev "$dev"
sysctl -qw "net.ipv4.conf.$dev.rp_filter=0" || true
sysctl -qw net.ipv4.conf.all.rp_filter=0 || true
# Let our SNAT rule own this destination, otherwise Cilium
# masquerades to a tunnel device that has no address.
iptables -t nat -C CILIUM_POST_nat -d "$HOME_LAN" -j RETURN 2>/dev/null \
|| iptables -t nat -I CILIUM_POST_nat 1 -d "$HOME_LAN" -j RETURN
iptables -t nat -C POSTROUTING -s "10.0.0.0/8" -d "$HOME_LAN" -j SNAT --to-source "169.254.8.$net" 2>/dev/null \
|| iptables -t nat -A POSTROUTING -s "10.0.0.0/8" -d "$HOME_LAN" -j SNAT --to-source "169.254.8.$net"
iptables -C FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \
|| iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -t mangle -C FORWARD -o "$dev" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss "$MSS" 2>/dev/null \
|| iptables -t mangle -A FORWARD -o "$dev" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss "$MSS"
iptables -t mangle -C FORWARD -i "$dev" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss "$MSS" 2>/dev/null \
|| iptables -t mangle -A FORWARD -i "$dev" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss "$MSS"
}
echo "home-lan-router: node=${NODE_NAME:-unknown} role=$(is_master && echo master || echo worker)"
while true; do
if is_master; then
master_loop
else
worker_loop
fi
sleep 60
done
env:
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: CONTROL_PLANE
valueFrom:
fieldRef:
fieldPath: "metadata.labels['node-role.kubernetes.io/control-plane']"
securityContext:
privileged: true
resources:
requests:
cpu: 10m
memory: 32Mi
limits:
memory: 64Mi
+1 -1
View File
@@ -43,7 +43,7 @@ spec:
containers:
- name: immich-server
image: "ghcr.io/immich-app/immich-server:v3"
imagePullPolicy: IfNotPresent
imagePullPolicy: Always
securityContext:
runAsUser: 0
ports:
+4 -1
View File
@@ -1,7 +1,7 @@
# kube-prometheus-stack Helm chart values
# Installed via:
# helm install kube-prometheus-stack prometheus-community/kube-prometheus-stack \
# --namespace monitoring --version 87.3.0 -f Monitoring/kube-prometheus-stack.values.yaml
# --namespace monitoring --version 88.6.1 -f Monitoring/kube-prometheus-stack.values.yaml
#
# Notes:
# - Bundled Grafana is disabled; the hand-managed Grafana in Monitoring/Grafana/
@@ -31,6 +31,9 @@ prometheus:
prometheusSpec:
# Match the previous manual deployment's retention.
retention: 15d
# Hard size cap: keep total TSDB size at/below 8GiB (~80% of the 10Gi PVC).
# Prevents a metric-cardinality spike from filling the Hetzner volume.
retentionSize: "8GB"
# Hetzner CSI volume, same class as the old prometheus-data PVC.
storageSpec:
+95
View File
@@ -0,0 +1,95 @@
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "rich",
# "ollama",
# ]
# ///
from typing import Union
from rich import print
import os
# client = Client(headers={'Authorization': f"Bearer {os.getenv('OLLAMA_API_KEY')}"} if api_key else None)
# --- MODIFICATION STARTS HERE ---
ollama_url = os.getenv("OLLAMA_API_BASE_URL")
if not ollama_url:
raise EnvironmentError("OLLAMA_API_BASE_URL environment variable must be set to connect to the Ollama service.")
client = Client(base_url=ollama_url, headers={'Authorization': f"Bearer {os.getenv('OLLAMA_API_KEY')}"} if os.getenv('OLLAMA_API_KEY') else None)
# --- MODIFICATION ENDS HERE ---
from ollama import WebFetchResponse, WebSearchResponse, chat, web_fetch, web_search
def format_tool_results(
results: Union[WebSearchResponse, WebFetchResponse],
user_search: str,
):
output = []
if isinstance(results, WebSearchResponse):
output.append(f'Search results for "{user_search}":')
for result in results.results:
output.append(f'{result.title}' if result.title else f'{result.content}')
output.append(f' URL: {result.url}')
output.append(f' Content: {result.content}')
output.append('')
return '\n'.join(output).rstrip()
elif isinstance(results, WebFetchResponse):
output.append(f'Fetch results for "{user_search}":')
output.extend(
[
f'Title: {results.title}',
f'URL: {user_search}' if user_search else '',
f'Content: {results.content}',
]
)
if results.links:
output.append(f'Links: {", ".join(results.links)}')
output.append('')
return '\n'.join(output).rstrip()
# client = Client(headers={'Authorization': f"Bearer {os.getenv('OLLAMA_API_KEY')}"} if api_key else None)
available_tools = {'web_search': web_search, 'web_fetch': web_fetch}
query = "what is ollama's new engine"
print('Query: ', query)
messages = [{'role': 'user', 'content': query}]
while True:
response = chat(model='qwen3', messages=messages, tools=[web_search, web_fetch], think=True)
if response.message.thinking:
print('Thinking: ')
print(response.message.thinking + '\n\n')
if response.message.content:
print('Content: ')
print(response.message.content + '\n')
messages.append(response.message)
if response.message.tool_calls:
for tool_call in response.message.tool_calls:
function_to_call = available_tools.get(tool_call.function.name)
if function_to_call:
args = tool_call.function.arguments
result: Union[WebSearchResponse, WebFetchResponse] = function_to_call(**args)
print('Result from tool call name:', tool_call.function.name, 'with arguments:')
print(args)
print()
user_search = args.get('query', '') or args.get('url', '')
formatted_tool_results = format_tool_results(result, user_search=user_search)
print(formatted_tool_results[:300])
print()
# caps the result at ~2000 tokens
messages.append({'role': 'tool', 'content': formatted_tool_results[: 2000 * 4], 'tool_name': tool_call.function.name})
else:
print(f'Tool {tool_call.function.name} not found')
messages.append({'role': 'tool', 'content': f'Tool {tool_call.function.name} not found', 'tool_name': tool_call.function.name})
else:
# no more tool calls, we can stop the loop
break
+253
View File
@@ -0,0 +1,253 @@
# Ollama / Open WebUI → Kubernetes migration plan
## Current state
- Ollama runs on the workstation `pop-os` as a systemd service (`/usr/local/bin/ollama serve`).
- It listens on `0.0.0.0:11434`.
- Local models are stored under `/usr/share/ollama/.ollama/models` (≈ 24 GB). The Kubernetes Ollama instance will **not** use these; it will use **Ollama Cloud models only**.
- The GPU is an NVIDIA GeForce RTX 2070 (8 GB VRAM) on `pop-os` — it stays on the workstation; Kubernetes has no GPU.
- The Kubernetes cluster currently runs on three Hetzner nodes with **no GPU** and **no NVIDIA device plugin**.
- Open WebUI runs on `pop-os` as a Docker container (`open-webui`), image `ghcr.io/open-webui/open-webui:main`, exposing host port `3000` mapped to container port `8080`.
- Open WebUI stores data in a Docker volume (`/var/lib/docker/volumes/open-webui/_data`, ≈ 1.4 GB) mounted at `/app/backend/data`.
- Current Open WebUI points to Ollama at `OLLAMA_BASE_URL=/ollama` via `host.docker.internal`.
- The Kubernetes cluster has an existing PostgreSQL instance (`postgres-hetzner` in the `database` namespace) with pgvector support.
## Goal
Move Ollama and Open WebUI into the existing Kubernetes cluster:
- Ollama will run **CPU-only** on the Hetzner nodes and use **Ollama Cloud models only**.
- Ollama is exposed **only inside the cluster** (Service `ollama.ollama.svc.cluster.local:11434`), no Ingress.
- Open WebUI is exposed on `chat.mariushome.lt` via Cilium dedicated LB Ingress.
- Open WebUI connects to the in-cluster Ollama service and uses the existing PostgreSQL for its main database and pgvector RAG store.
- This is a **fresh start** for Open WebUI data: existing chats/settings on `pop-os` are not migrated to PostgreSQL.
- `pop-os` Ollama will be shut down after the migration.
## Important limitation / warning
The Hetzner worker nodes have only **~7.8 GB allocatable memory** and the master only **~3.8 GB**. Because Kubernetes Ollama uses **Ollama Cloud models only**, it does not download or run large models locally, so the small CPU/memory footprint is safe. If you later want to run local models in Kubernetes, you must add a larger/GPU node.
## Manifests added
All manifests are in `Ollama/`:
| File | Purpose |
|------|---------|
| `ollama_namespace.yaml` | `ollama` namespace (shared) |
| `ollama_pvc.yaml` | PVC for Ollama state on `slow` StorageClass |
| `ollama_secret_example.yaml` | Example Secret for `OLLAMA_API_KEY` (do NOT commit) |
| `ollama_deployment.yaml` | CPU-only Ollama Deployment with cloud API key + PVC |
| `ollama_service.yaml` | ClusterIP Service `ollama:11434` |
| `openwebui_secret_example.yaml` | Example Secret with admin credentials and DB URLs (do NOT commit) |
| `openwebui_db_setup.yaml` | One-time Job to create the `openwebui` DB/user in PostgreSQL |
| `openwebui_deployment.yaml` | Open WebUI Deployment (PostgreSQL + pgvector) |
| `openwebui_service.yaml` | ClusterIP Service `open-webui:8080` |
| `openwebui_ingress.yaml` | Cilium dedicated LB ingress `chat.mariushome.lt` |
| `openwebui_imagegen_config.yaml` | ConfigMap `openwebui-imagegen` — enables ComfyUI image generation (see below) |
## Image generation (ComfyUI on pop-os)
Image generation runs on the `pop-os` workstation (RTX 2070, 8 GB) where ComfyUI
listens on `http://192.168.8.28:8188`. The cluster reaches it over the home-gw /
WireGuard route: every node has a route for `192.168.8.0/24` (master via `wg0`,
workers via `home-gw` with SNAT `10.0.0.0/8 → 169.254.8.x`), so pods can connect
directly. No tunnel or master proxy is needed.
- `openwebui_imagegen_config.yaml` (`openwebui-imagegen` ConfigMap) sets
`ENABLE_IMAGE_GENERATION=true`, `IMAGE_GENERATION_ENGINE=comfyui`,
`IMAGE_GENERATION_MODEL=qwen-image`, `IMAGE_SIZE`, `IMAGE_STEPS`, and the full
`COMFYUI_WORKFLOW` / `COMFYUI_WORKFLOW_NODES` (Qwen-Image 2512 + Lightning
4-step txt2img).
- `openwebui_deployment.yaml` consumes it via `envFrom.configMapRef`.
- **PersistentConfig caveat:** Open WebUI stores `image_generation.*` in the
`config` table of the `openwebui` Postgres DB, and **DB values override env**.
Setting the ConfigMap alone is not enough on an existing install — the DB rows
must match too. Either use Admin → Settings → Images, or update the DB:
```bash
POD=$(kubectl -n database get pods -l app=postgres-hetzner -o jsonpath='{.items[0].metadata.name}')
kubectl -n database exec $POD -- sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -U "${POSTGRES_USER:-admin}" -d openwebui' <<'SQL'
UPDATE config SET value='true'::json WHERE key='image_generation.enable';
UPDATE config SET value=to_json('comfyui'::text) WHERE key='image_generation.engine';
UPDATE config SET value=to_json('qwen-image'::text) WHERE key='image_generation.model';
UPDATE config SET value=to_json('http://192.168.8.28:8188'::text) WHERE key='image_generation.comfyui.base_url';
SQL
```
- Requirements on pop-os: ComfyUI bound to the LAN (`--listen ...,192.168.8.28`,
handled by `comfy-mode`), static IP `192.168.8.28`, and the machine powered on
(generation fails while it is offline/asleep).
## Storage
### Ollama
Kubernetes Ollama uses **Ollama Cloud models only**, so no model blobs are stored locally. The Deployment mounts a PVC (`slow` StorageClass) at `/root/.ollama` to persist the Ollama Cloud login session / API key state across pod restarts.
### Ollama Cloud authentication
Ollama Cloud models require authentication. Two options:
1. **API key (recommended for Kubernetes)**: create an API key at https://ollama.com/settings/keys, then create the `ollama-cloud` Secret from `ollama_secret_example.yaml`. The Deployment injects `OLLAMA_API_KEY` automatically.
2. **Interactive signin**: exec into the pod and run `ollama signin`:
```bash
kubectl -n ollama exec -it deploy/ollama -- ollama signin
```
Because `/root/.ollama` is now persisted on a PVC, the session survives pod restarts.
### Open WebUI
Open WebUI uses the existing PostgreSQL (`postgres-hetzner.database.svc.cluster.local:5432`) for both the main relational database and the pgvector vector store. Uploaded files are still written to `/app/backend/data`, but since this is a fresh install, an `emptyDir` is sufficient.
If you later want persistence for uploads, create a small PVC using the **`slow`** StorageClass (SMB CSI — the cluster default). Do **not** use `hcloud-volumes` for Open WebUI uploads. Example:
```yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: open-webui-uploads
namespace: ollama
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 10Gi
storageClassName: slow
```
## Pre-deployment database setup
1. The existing `postgres-secret` in the `database` namespace already contains the superuser password, so no new Secret is needed.
2. Edit `Ollama/openwebui_db_setup.yaml` and replace the placeholder password `openwebui-password` in the `CREATE USER` statement with a strong, unique password.
3. Create the database and user:
```bash
kubectl apply -f Ollama/openwebui_db_setup.yaml
kubectl wait job/openwebui-db-setup -n database --for=condition=complete
kubectl delete -f Ollama/openwebui_db_setup.yaml
```
If the user/database already exists from a previous run with the old password, drop them first (requires the postgres superuser):
```bash
kubectl run -it --rm -n database psql-cleanup --image=rg.mariushome.lt/custom-postgres --restart=Never --env="PGUSER=admin" --env="PGPASSWORD=$(kubectl get secret -n database postgres-secret -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d)" -- psql -h postgres.database.svc.cluster.local -d postgres -c "DROP DATABASE IF EXISTS openwebui; DROP USER IF EXISTS openwebui;"
```
## Secret creation (interactive)
The `openwebui-secret` must be created out-of-band because it contains passwords. Use the helper script and enter the same password you set in `openwebui_db_setup.yaml`:
```bash
./Ollama/create_openwebui_secret.sh
```
Or create it manually, replacing `YOUR-OPENWEBUI-DB-PASSWORD` with the password from `openwebui_db_setup.yaml`:
```bash
kubectl create secret generic -n ollama openwebui-secret \
--from-literal=WEBUI_SECRET_KEY="977a7a4e9051d31575f17ed7610c7bf7f9af9475205cc636ead271e699f1a680" \
--from-literal=WEBUI_ADMIN_EMAIL="admin@mariushome.lt" \
--from-literal=WEBUI_ADMIN_PASSWORD="fsbubSHADBJKASDs4s4ds5" \
--from-literal=DATABASE_URL="postgresql://openwebui:YOUR-OPENWEBUI-DB-PASSWORD@postgres-hetzner.database.svc.cluster.local:5432/openwebui" \
--from-literal=PGVECTOR_DB_URL="postgresql://openwebui:YOUR-OPENWEBUI-DB-PASSWORD@postgres-hetzner.database.svc.cluster.local:5432/openwebui"
```
## Rollout steps
1. Recreate the `openwebui` database/user with the new password (see "Pre-deployment database setup" above).
2. Create the Open WebUI namespace:
```bash
kubectl apply -f Ollama/ollama_namespace.yaml
```
3. Create the `openwebui-secret` interactively (see "Secret creation" above) using the new password.
4. Create the Ollama PVC and (optionally) cloud Secret:
```bash
# PVC for /root/.ollama state
kubectl apply -f Ollama/ollama_pvc.yaml
# Optional: if using an Ollama Cloud API key, create the Secret first:
# (Get your key from https://ollama.com/settings/keys)
kubectl apply -f Ollama/ollama_secret_example.yaml
```
5. Apply Ollama manifests:
```bash
kubectl apply -f Ollama/ollama_service.yaml
kubectl apply -f Ollama/ollama_deployment.yaml
```
6. Verify Ollama is running and accessible inside the cluster:
```bash
kubectl -n ollama get pods -o wide
kubectl -n ollama logs -f deploy/ollama
kubectl -n ollama exec -it deploy/ollama -- ollama list
```
7. Apply Open WebUI manifests:
```bash
kubectl apply -f Ollama/openwebui_service.yaml
kubectl apply -f Ollama/openwebui_deployment.yaml
kubectl apply -f Ollama/openwebui_ingress.yaml
```
8. Verify:
```bash
kubectl -n ollama get pods -o wide
kubectl -n ollama logs -f deploy/open-webui
kubectl -n ollama get ingress
```
9. Update DNS for `chat.mariushome.lt` to point to the Cilium LB IP assigned to the `open-webui` Ingress.
10. After confirming Open WebUI works on `chat.mariushome.lt`, shut down the local `pop-os` services (keep the Docker volume as a backup):
```bash
sudo systemctl stop ollama
sudo systemctl disable ollama
docker stop open-webui
# Keep the volume for backup; only remove the container.
docker rm open-webui
```
## Client / consumer reconfiguration
- Update Open WebUI access from `http://pop-os:3000` to `http://chat.mariushome.lt`.
- Ollama consumers inside the cluster should use `http://ollama.ollama.svc.cluster.local:11434`. No external Ollama endpoint is exposed.
- For OpenCode, change the Ollama host to `http://ollama.ollama.svc.cluster.local:11434` if OpenCode runs inside the cluster, or use the Open WebUI endpoint externally.
## Important security notes
- Ollama is **not exposed via Ingress**; it is reachable only inside the cluster.
- Open WebUI is exposed on `chat.mariushome.lt` inside the LAN. Do not publish it to the public Internet without an authenticating proxy.
- Signups are disabled (`ENABLE_SIGNUP=false`). The initial admin account is bootstrapped from the Secret.
- `openwebui_secret_example.yaml` and `openwebui_db_setup.yaml` contain sensitive values and must be created out-of-band; do not commit them.
## Rollback
```bash
kubectl delete -f Ollama/openwebui_ingress.yaml
kubectl delete -f Ollama/openwebui_deployment.yaml
kubectl delete -f Ollama/openwebui_service.yaml
kubectl delete -f Ollama/ollama_deployment.yaml
kubectl delete -f Ollama/ollama_service.yaml
# Restart local services on pop-os if needed:
sudo systemctl start ollama
docker start open-webui
```
## Decisions made
- The `openwebui` PostgreSQL user must use a **different password than the example `openwebui-password`**. Edit `openwebui_db_setup.yaml`, replace the password in the `CREATE USER` statement, and re-run the Job to recreate the user/database before creating the `openwebui-secret`.
- The `pop-os` Open WebUI Docker data (`/var/lib/docker/volumes/open-webui/_data`, ≈ 1.4 GB) will be **kept as a backup** after shutdown. Do not delete the Docker volume when stopping the container.
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
set -euo pipefail
# Helper script to create the openwebui-secret without committing passwords.
# Run interactively and enter the password when prompted.
NAMESPACE="ollama"
SECRET_NAME="openwebui-secret"
echo "=== Create Kubernetes secret for Open WebUI ==="
read -rsp "Enter password for the 'openwebui' PostgreSQL user: " DB_PASSWORD
echo
read -rsp "Enter WEBUI_SECRET_KEY (or press Enter to auto-generate one): " SECRET_KEY
echo
if [[ -z "$SECRET_KEY" ]]; then
SECRET_KEY=$(openssl rand -hex 32)
echo "Auto-generated WEBUI_SECRET_KEY: $SECRET_KEY"
fi
read -rp "Enter Open WebUI admin email [admin@mariushome.lt]: " ADMIN_EMAIL
ADMIN_EMAIL=${ADMIN_EMAIL:-admin@mariushome.lt}
read -rsp "Enter Open WebUI admin password [fsbubSHADBJKASDs4s4ds5]: " ADMIN_PASSWORD
echo
ADMIN_PASSWORD=${ADMIN_PASSWORD:-fsbubSHADBJKASDs4s4ds5}
DATABASE_URL="postgresql://openwebui:${DB_PASSWORD}@postgres-hetzner.database.svc.cluster.local:5432/openwebui"
PGVECTOR_DB_URL="postgresql://openwebui:${DB_PASSWORD}@postgres-hetzner.database.svc.cluster.local:5432/openwebui"
kubectl create secret generic -n "$NAMESPACE" "$SECRET_NAME" \
--from-literal=WEBUI_SECRET_KEY="$SECRET_KEY" \
--from-literal=WEBUI_ADMIN_EMAIL="$ADMIN_EMAIL" \
--from-literal=WEBUI_ADMIN_PASSWORD="$ADMIN_PASSWORD" \
--from-literal=DATABASE_URL="$DATABASE_URL" \
--from-literal=PGVECTOR_DB_URL="$PGVECTOR_DB_URL" \
--dry-run=client -o yaml | kubectl apply -f -
echo "Secret '$SECRET_NAME' created/updated in namespace '$NAMESPACE'."
+73
View File
@@ -0,0 +1,73 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: ollama
namespace: ollama
labels:
app: ollama
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: ollama
template:
metadata:
labels:
app: ollama
spec:
# CPU-only Ollama running on Hetzner nodes. No GPU available.
containers:
- name: ollama
image: ollama/ollama:0.32.4
imagePullPolicy: IfNotPresent
env:
- name: OLLAMA_HOST
value: "0.0.0.0:11434"
# Optional: keep models loaded for N minutes after last use (e.g. 15m).
# - name: OLLAMA_KEEP_ALIVE
# value: "15m"
# Ollama Cloud API key for cloud models. Create the ollama-cloud Secret
# from ollama_secret_example.yaml, or sign in with `ollama signin`.
- name: OLLAMA_API_KEY
valueFrom:
secretKeyRef:
name: ollama-cloud
key: OLLAMA_API_KEY
optional: true
ports:
- containerPort: 11434
name: http
protocol: TCP
# OllamaCloud-only: no local model execution, so CPU/RAM needs are minimal.
resources:
requests:
cpu: "100m"
memory: 512Mi
limits:
cpu: "1"
memory: 1Gi
livenessProbe:
httpGet:
path: /
port: 11434
initialDelaySeconds: 30
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 6
readinessProbe:
httpGet:
path: /
port: 11434
initialDelaySeconds: 10
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 6
volumeMounts:
- name: ollama-state
mountPath: /root/.ollama
volumes:
- name: ollama-state
persistentVolumeClaim:
claimName: ollama-state
+19
View File
@@ -0,0 +1,19 @@
apiVersion: v1
kind: Service
metadata:
name: ollama-lb
namespace: ollama
labels:
app: ollama
io.cilium/static-ip: "true"
annotations:
lbipam.cilium.io/ips: 10.2.0.123
spec:
type: LoadBalancer
selector:
app: ollama
ports:
- name: http
port: 11434
targetPort: 11434
protocol: TCP
+6
View File
@@ -0,0 +1,6 @@
apiVersion: v1
kind: Namespace
metadata:
name: ollama
labels:
app: ollama
+14
View File
@@ -0,0 +1,14 @@
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: ollama-state
namespace: ollama
labels:
app: ollama
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 5Gi
storageClassName: slow
+16
View File
@@ -0,0 +1,16 @@
apiVersion: v1
kind: Service
metadata:
name: ollama
namespace: ollama
labels:
app: ollama
spec:
type: ClusterIP
selector:
app: ollama
ports:
- name: http
port: 11434
targetPort: 11434
protocol: TCP
+47
View File
@@ -0,0 +1,47 @@
# Run this init job once to create the Open WebUI database and user on the
# existing postgres-hetzner instance.
#
# This manifest references the existing postgres-secret in the database namespace.
# If your secret has a different name or key, update the env block below.
#
# Then:
# 1. kubectl apply -f Ollama/openwebui_db_setup.yaml
# 2. kubectl wait job/openwebui-db-setup -n database --for=condition=complete
# 3. kubectl delete -f Ollama/openwebui_db_setup.yaml
apiVersion: batch/v1
kind: Job
metadata:
name: openwebui-db-setup
namespace: database
spec:
template:
spec:
restartPolicy: OnFailure
imagePullSecrets:
- name: registry-creds
containers:
- name: psql
image: rg.mariushome.lt/custom-postgres
imagePullPolicy: Always
env:
- name: PGUSER
valueFrom:
secretKeyRef:
name: postgres-secret
key: POSTGRES_USER
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: POSTGRES_PASSWORD
command:
- /bin/sh
- -c
- |
psql -h postgres.database.svc.cluster.local -d postgres -e <<'SQL'
CREATE USER openwebui WITH PASSWORD '6b44a0043b23368a18b6aa940dd30ae7299a77dcd2e555f554c51066a1e4e76f';
CREATE DATABASE openwebui OWNER openwebui;
\c openwebui
CREATE EXTENSION IF NOT EXISTS vector;
GRANT ALL PRIVILEGES ON DATABASE openwebui TO openwebui;
SQL
+107
View File
@@ -0,0 +1,107 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: open-webui
namespace: ollama
labels:
app: open-webui
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: open-webui
template:
metadata:
labels:
app: open-webui
spec:
containers:
- name: open-webui
image: ghcr.io/open-webui/open-webui:main
imagePullPolicy: Always
envFrom:
# Image generation (ComfyUI on pop-os). See openwebui_imagegen_config.yaml.
- configMapRef:
name: openwebui-imagegen
env:
- name: OLLAMA_BASE_URL
value: "http://ollama.ollama.svc.cluster.local:11434"
- name: WEBUI_URL
value: "http://chat.mariushome.lt"
- name: PORT
value: "8080"
- name: ENABLE_SIGNUP
value: "false"
- name: ENABLE_LOGIN_FORM
value: "true"
- name: ENABLE_RAG
value: "true"
- name: RAG_EMBEDDING_ENGINE
value: "ollama"
- name: RAG_EMBEDDING_MODEL
value: "nomic-embed-text"
- name: VECTOR_DB
value: "pgvector"
- name: ENABLE_PERSISTENT_CONFIG
value: "true"
- name: WEBUI_SECRET_KEY
valueFrom:
secretKeyRef:
name: openwebui-secret
key: WEBUI_SECRET_KEY
- name: WEBUI_ADMIN_EMAIL
valueFrom:
secretKeyRef:
name: openwebui-secret
key: WEBUI_ADMIN_EMAIL
- name: WEBUI_ADMIN_PASSWORD
valueFrom:
secretKeyRef:
name: openwebui-secret
key: WEBUI_ADMIN_PASSWORD
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: openwebui-secret
key: DATABASE_URL
- name: PGVECTOR_DB_URL
valueFrom:
secretKeyRef:
name: openwebui-secret
key: PGVECTOR_DB_URL
ports:
- containerPort: 8080
name: http
protocol: TCP
resources:
requests:
cpu: "250m"
memory: 512Mi
limits:
cpu: "2"
memory: 4Gi
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 60
periodSeconds: 30
timeoutSeconds: 5
failureThreshold: 5
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 5
# Fresh PostgreSQL install: uploads go to emptyDir. Add a PVC later if needed.
volumeMounts:
- name: data
mountPath: /app/backend/data
volumes:
- name: data
emptyDir: {}
+22
View File
@@ -0,0 +1,22 @@
# Image generation config for Open WebUI (Kubernetes).
# Points Open WebUI at ComfyUI running on pop-os (GPU), reachable from the
# cluster via the home-gw / WireGuard route to 192.168.8.0/24.
# The workflow below is the Qwen-Image 2512 + Lightning 4-step text-to-image
# graph (matches ~/comfy/workflows/openwebui_qwen_t2i.json on pop-os).
apiVersion: v1
kind: ConfigMap
metadata:
name: openwebui-imagegen
namespace: ollama
labels:
app: open-webui
data:
ENABLE_IMAGE_GENERATION: "true"
IMAGE_GENERATION_ENGINE: "comfyui"
IMAGE_GENERATION_MODEL: "qwen-image"
IMAGE_SIZE: "1024x1024"
IMAGE_STEPS: "4"
COMFYUI_BASE_URL: "http://192.168.8.28:8188"
COMFYUI_API_KEY: ""
COMFYUI_WORKFLOW: '{"1":{"class_type":"UnetLoaderGGUF","inputs":{"unet_name":"qwen-image-Q4_K_M.gguf"}},"2":{"class_type":"CLIPLoader","inputs":{"clip_name":"qwen_2.5_vl_7b_fp8_scaled.safetensors","type":"qwen_image","device":"default"}},"3":{"class_type":"VAELoader","inputs":{"vae_name":"qwen_image_vae.safetensors"}},"4":{"class_type":"LoraLoaderModelOnly","inputs":{"model":["1",0],"lora_name":"Qwen-Image-2512-Lightning-4steps-V1.0-fp32.safetensors","strength_model":1.0}},"5":{"class_type":"ModelSamplingAuraFlow","inputs":{"model":["4",0],"shift":3.1}},"6":{"class_type":"CLIPTextEncode","inputs":{"clip":["2",0],"text":""}},"7":{"class_type":"CLIPTextEncode","inputs":{"clip":["2",0],"text":""}},"8":{"class_type":"EmptySD3LatentImage","inputs":{"width":1024,"height":1024,"batch_size":1}},"9":{"class_type":"KSampler","inputs":{"model":["5",0],"positive":["6",0],"negative":["7",0],"latent_image":["8",0],"seed":42,"steps":4,"cfg":1.0,"sampler_name":"euler","scheduler":"simple","denoise":1.0}},"10":{"class_type":"VAEDecode","inputs":{"samples":["9",0],"vae":["3",0]}},"11":{"class_type":"SaveImage","inputs":{"images":["10",0],"filename_prefix":"openwebui_qwen"}}}'
COMFYUI_WORKFLOW_NODES: '[{"type":"prompt","node_ids":["6"],"key":"text"},{"type":"negative_prompt","node_ids":["7"],"key":"text"},{"type":"width","node_ids":["8"],"key":"width"},{"type":"height","node_ids":["8"],"key":"height"},{"type":"n","node_ids":["8"],"key":"batch_size"},{"type":"steps","node_ids":["9"],"key":"steps"},{"type":"seed","node_ids":["9"],"key":"seed"}]'
+20
View File
@@ -0,0 +1,20 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: open-webui
namespace: ollama
annotations:
ingress.cilium.io/loadbalancer-mode: "dedicated"
spec:
ingressClassName: cilium
rules:
- host: chat.mariushome.lt
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: open-webui
port:
number: 8080
+16
View File
@@ -0,0 +1,16 @@
apiVersion: v1
kind: Service
metadata:
name: open-webui
namespace: ollama
labels:
app: open-webui
spec:
type: ClusterIP
selector:
app: open-webui
ports:
- name: http
port: 8080
targetPort: 8080
protocol: TCP
+64
View File
@@ -0,0 +1,64 @@
# PostgreSQL Backup Plan — Hetzner Storage Box
Goal: automated backups of the `postgres-hetzner` database (namespace `database`)
to an off-cluster Hetzner Storage Box, using the plain-manifest style of this repo.
## Current state
- Postgres: single-replica Deployment `postgres-hetzner`, ns `database`,
data on `hcloud-volumes` PVC (`postgres-hetzner-pvc`).
- Image: `rg.mariushome.lt/custom-postgres` (postgres 18.4 + pgvector,
**already contains rclone** — can talk SFTP directly, no new image build needed).
- Credentials live in existing `postgres-secret` (POSTGRES_USER / POSTGRES_PASSWORD).
- No backup automation exists today.
## Proposed approach
CronJob + `pg_dump` + `rclone` over SFTP (logical backups, no sidecar,
no new Docker image, no extra PVC — stream dump into `rclone rcat`).
### 1. Storage Box (one-time, manual)
- Create sub-account/directory, e.g. `postgres-backups/`.
- SFTP endpoint: `uXXXXX@uXXXXX.your-storagebox.de:23`.
### 2. Secrets (gitignored — never committed)
- New Secret `postgres-backup-secret` in `database` ns:
- `SFTP_HOST`, `SFTP_USER`, `SFTP_PASS` (or `SFTP_KEY`).
- DB credentials reused from existing `postgres-secret`.
### 3. New manifests — `PostgreSQL/backup/`
- `postgres_backup_rclone_configmap.yaml` — rclone.conf with `storagebox:` SFTP remote.
- `postgres_backup_cronjob.yaml` — CronJob:
- schedule: (TBD, e.g. daily `0 3 * * *`)
- image `rg.mariushome.lt/custom-postgres`
- command: `pg_dumpall | rclone rcat storagebox:postgres-backups/dump-$(date).pgdump`
- retention: `rclone delete --min-age Nd` (TBD) before/after upload
- `concurrencyPolicy: Forbid`, history limits 1/1
- `backoffLimit: 2`
### 4. Verification
- Test run: `kubectl create job --from=cronjob/postgres-backup backup-test -n database`
- Check logs; verify file on Storage Box via `rclone lsd` from a debug pod.
- Document restore procedure (`pg_restore` / `psql`) in this file after first successful backup.
### 5. Later (optional)
- PrometheusRule alert on failed/timed-out CronJob (kube-prometheus-stack already selects all).
- Restore drill runbook.
## Open questions (fill in before implementation)
1. **Backup scope**: `pg_dumpall` (all DBs + roles/globals) vs. per-database `pg_dump` loop? →
2. **Physical vs. logical**: logical `pg_dumpall` assumed OK (small homelab DB, simple restore). PITR/WAL archiving is out of scope — confirm? →
3. **Schedule**: e.g. daily at 03:00 UTC? →
4. **Retention**: keep N days? also keep weeklies/monthlies? →
5. **Storage Box auth**: SSH key or password? →
6. **Storage Box host/account**: hostname + username once the sub-account exists? →
7. **Backup filename scheme**: OK with `postgres-backup-YYYYMMDD-HHMM.pgdump`? →
8. **Alerting**: add PrometheusRule for failed CronJob now, or later? →
## Notes / constraints
- Dump size must fit in pod ephemeral storage if not streaming; streaming via
`rclone rcat` avoids any local disk requirement.
- Storage Box SFTP uses port 23 (Hetzner default).
- Downtime is NOT required — `pg_dumpall` is online and consistent per DB.
-240
View File
@@ -1,240 +0,0 @@
# PostgreSQL Migration Runbook
Migrate the `postgres` database from the old StatefulSet (local-storage, image `pgvector/pgvector:pg18-trixie`) to a new Deployment `postgres-hetzner` on `hcloud-volumes` (Hetzner CSI), using the public image `pgvector/pgvector:pg18-trixie` (Postgres 18 + pgvector 0.8.2).
**Strategy:** logical dump/restore via `pg_dumpall`, Option A service repoint (external IP `10.2.0.122` and internal DNS `postgres.database.svc.cluster.local` both unchanged → outside dependency and in-cluster consumers need no reconfiguration).
**Downtime:** required (writers stopped during dump/restore). Estimated window: ~20–40 min depending on 18 GB transfer speed.
---
## Current state (verified in cluster)
### Old DB
- **StatefulSet** `postgres` in namespace `database` (120 days old).
- **Pod** `postgres-0` on node `woker-1-8gb-hel1-1`, IP `10.0.2.116`.
- **Image:** `pgvector/pgvector:pg18-trixie` (Postgres 18 + pgvector).
- **Credentials:** hardcoded `POSTGRES_USER=admin`, `POSTGRES_PASSWORD=jd@wXseh9z7vM@9`. Also stored in Secret `postgres-secret` (namespace `database`) with the same values.
- **PVC** `postgres-data-postgres-0` (from STS `volumeClaimTemplates`): `local-storage`, 30Gi requested, bound to PV `example-pv` (50Gi).
### Services (two)
1. **`postgres`** — ClusterIP `10.107.200.144`, selector `app: postgres`. **Internal DNS** `postgres.database.svc.cluster.local` used by in-cluster consumers.
2. **`postgres-service`** — LoadBalancer, **external IP `10.2.0.122`** (annotation `lbipam.cilium.io/ips: 10.2.0.122`, pool `postgres-pool` CIDR `10.2.0.0/24`), selector `app: postgres`. **Used by the outside dependency.**
### Cilium LB IP pools
- `lan-pool` → `10.1.0.101–10.1.0.199` (94 free) — used by Cilium ingresses.
- `postgres-pool` → `10.2.0.0/24` (255 free, 1 used = `10.2.0.122`) — dedicated postgres pool.
### Databases to migrate (~18.4 GB total)
| Database | Size | Owner | Used by |
|---|---|---|---|
| homeassistant | 18 GB | homeassistant | outside dependency (via LB `10.2.0.122`) |
| immich | 445 MB | admin | immich-server, immich-machine-learning |
| gitea | 15 MB | gitea | gitea |
| grafana | 14 MB | grafana | grafana |
| backup | 8.5 MB | data_mover | (legacy) |
| admin | 7.7 MB | admin | — |
### `immich` DB extensions (must be present in new image)
`cube`, `earthdistance`, `pg_trgm`, `unaccent`, `uuid-ossp`, `vector (0.8.2)`, `plpgsql`.
All present in the custom image (`postgres:18.4` + `pgvector v0.8.2`) and in `pgvector/pgvector:pg18-trixie`.
### Consumers of `postgres.database.svc.cluster.local` (all unchanged with Option A)
| Consumer | Namespace | Deployment |
|---|---|---|
| immich-server | immich | immich-server |
| immich-machine-learning | immich | immich-machine-learning |
| gitea | gitea | gitea |
| grafana | monitoring | grafana |
### External consumer
- **The outside dependency connects via the old pod IP `10.0.2.116` (NOT the LB `10.2.0.122`).** This was incorrect — pod IPs are ephemeral and disappear when the pod is deleted.
- After migration, the old pod IP `10.0.2.116` is gone. The outside dependency **must be reconfigured to use `10.2.0.122:5432`** (the stable LB IP, which routes to the new `postgres-hetzner` pod).
- The LB `postgres-service` keeps IP `10.2.0.122` via the Cilium annotation `lbipam.cilium.io/ips: 10.2.0.122` (pool `postgres-pool`) — this IP is stable across pod restarts/replacements.
- **Action required:** update the outside dependency's DB host from `10.0.2.116` → `10.2.0.122` before/after cutover.
---
## Repo manifest changes (already applied)
- `PostgreSQL/postgress_deplay.yaml` — synced to live STS (rollback reference).
- `PostgreSQL/postgres_service.yaml` — ClusterIP `postgres`, selector `app: postgres-hetzner`.
- `PostgreSQL/postgres_lb_service.yaml` (new) — LB `postgres-service`, static IP `10.2.0.122`, selector `app: postgres-hetzner`.
- `PostgreSQL/hetzner/postgres_hetzner_deployment.yaml` — uses `postgres-secret` (secretKeyRef), public image `pgvector/pgvector:pg18-trixie` (custom image `10.0.2.119:5000/custom-postgres:latest` not reachable — old node IP gone; nodes now on 10.1.0.x and cluster DNS not resolvable from node containerd), `strategy: Recreate`.
- Removed stale `postgres_pvc.yaml` and `postgres_static_endpoint.yaml`.
---
## Execution
### Phase 0 — Pre-flight (re-run on migration day to confirm no drift)
```bash
kubectl get pvc -n database
kubectl get sts,deploy,svc,pod,endpointslice -n database
kubectl exec -n database postgres-0 -- psql -U admin -d postgres -c '\l+'
kubectl get svc postgres-service -n database -o jsonpath='{.status.loadBalancer.ingress[0].ip}' # expect 10.2.0.122
# Confirm new objects don't exist yet
kubectl get deploy postgres-hetzner -n database # expect NotFound
kubectl get pvc postgres-hetzner-pvc -n database # expect NotFound
```
### Phase 1 — Stand up new empty DB (no downtime yet)
```bash
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_pvc.yaml
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_secret.yml
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_deployment.yaml
kubectl apply -f PostgreSQL/hetzner/postgres_hetzner_service.yaml # temp internal svc for restore
kubectl rollout status deploy/postgres-hetzner -n database
kubectl get pod -n database -l app=postgres-hetzner -w # wait Running
```
### Phase 2 — Downtime begins, stop ALL writers
```bash
kubectl scale deploy/immich-server -n immich --replicas=0
kubectl scale deploy/immich-machine-learning -n immich --replicas=0
kubectl scale deploy/gitea -n gitea --replicas=0
kubectl scale deploy/grafana -n monitoring --replicas=0
# >>> STOP the outside dependency writing to homeassistant DB now <<<
# confirm all stopped
kubectl get pod -n immich -l app=immich-server
kubectl get pod -n immich -l app=immich-machine-learning
kubectl get pod -n gitea -l app=gitea
kubectl get pod -n monitoring -l app=grafana
```
### Phase 3 — Dump + restore (writers down = consistent ~18.4 GB)
> **IMPORTANT:** Do NOT use `pg_dumpall | psql` over a `kubectl exec` pipe. The kubectl websocket times out on large transfers (~18 GB) and the text format corrupts `vector` data (long embedding strings get truncated, breaking `smart_search` and other pgvector tables). Use binary `pg_dump -Fc` with `pg_restore`, running `pg_dump` from inside the new pod pointing at the old DB via the `postgres` Service.
```bash
OLD=$(kubectl get pod -n database -l app=postgres -o jsonpath='{.items[0].metadata.name}')
NEW=$(kubectl get pod -n database -l app=postgres-hetzner -o jsonpath='{.items[0].metadata.name}')
echo "OLD=$OLD NEW=$NEW"
# Step 1: pg_dumpall for roles + small DBs (admin, backup, postgres, gitea, grafana) via text pipe
# — these have no vector data and are small (<15 MB each), safe over kubectl pipe.
kubectl exec -n database $OLD -- pg_dumpall -c -U admin --roles-only \
| kubectl exec -i -n database $NEW -- psql -U admin -d postgres
# Create the small databases (gitea, grafana, backup, homeassistant) — schema only first if needed,
# or rely on pg_dumpall to recreate them. For non-immich DBs, text pipe is fine (no vector columns):
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d gitea -f /tmp/gitea.dump
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d grafana -f /tmp/grafana.dump
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d backup -f /tmp/backup.dump
kubectl exec -n database $OLD -- pg_dump -U admin -Fc -d homeassistant -f /tmp/homeassistant.dump
# Transfer each dump from old pod to new pod using pg_dump from the new pod (binary-safe, avoids kubectl pipe):
for db in gitea grafana backup homeassistant immich; do
kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
pg_dump -h postgres.database.svc.cluster.local -U admin -d $db -Fc -f /tmp/$db.dump
done
# Step 2: restore each DB on the new pod (drop existing first if re-running)
for db in gitea grafana backup homeassistant immich; do
kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
psql -h localhost -U admin -d postgres -c "DROP DATABASE IF EXISTS $db;"
kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
psql -h localhost -U admin -d postgres -c "CREATE DATABASE $db OWNER admin;"
kubectl exec -n database $NEW -- env PGPASSWORD='jd@wXseh9z7vM@9' \
pg_restore -h localhost -U admin -d $db --no-owner --no-privileges /tmp/$db.dump
done
# Step 3: verify DBs + sizes
kubectl exec -n database $NEW -- psql -U admin -d postgres -c '\l+'
# verify immich extensions
kubectl exec -n database $NEW -- psql -U admin -d immich -c "\dx"
# spot-check row counts
kubectl exec -n database $NEW -- psql -U admin -d immich -c "SELECT count(*) FROM asset;"
kubectl exec -n database $NEW -- psql -U admin -d immich -c "SELECT count(*) FROM smart_search;"
kubectl exec -n database $NEW -- psql -U admin -d homeassistant -c "SELECT count(*) FROM events;"
kubectl exec -n database $NEW -- psql -U admin -d gitea -c "SELECT count(*) FROM repository;"
kubectl exec -n database $NEW -- psql -U admin -d grafana -c "SELECT count(*) FROM dashboard;"
# Step 4: cleanup dump files
for db in gitea grafana backup homeassistant immich; do
kubectl exec -n database $NEW -- rm -f /tmp/$db.dump
kubectl exec -n database $OLD -- rm -f /tmp/$db.dump 2>/dev/null
done
```
**Why dump from the new pod:** the new pod can reach the old DB via `postgres.database.svc.cluster.local` (still pointing at old pods until cutover), and writes the binary dump file directly to its own PVC — no kubectl pipe, no truncation, no websocket timeout.
### Phase 4 — Cutover (repoint both Services to new pods)
```bash
kubectl apply -f PostgreSQL/postgres_service.yaml # ClusterIP postgres → app: postgres-hetzner
kubectl apply -f PostgreSQL/postgres_lb_service.yaml # LB postgres-service → app: postgres-hetzner, IP 10.2.0.122 kept
kubectl get svc postgres postgres-service -n database
# verify external IP still 10.2.0.122
kubectl get svc postgres-service -n database -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
# verify in-cluster connectivity via the unchanged DNS name
kubectl run pg-test --rm -it --image=postgres:18 --restart=Never -- \
psql -h postgres.database.svc.cluster.local -U admin -d postgres -c '\l+'
```
### Phase 5 — Restart consumers (immich's initContainer pg_isready validates)
```bash
kubectl scale deploy/immich-server -n immich --replicas=1
kubectl scale deploy/immich-machine-learning -n immich --replicas=1
kubectl scale deploy/gitea -n gitea --replicas=1
kubectl scale deploy/grafana -n monitoring --replicas=1
kubectl rollout status deploy/immich-server -n immich
kubectl rollout status deploy/gitea -n gitea
kubectl rollout status deploy/grafana -n monitoring
kubectl logs deploy/immich-server -n immich --tail=50 # no DB errors
kubectl logs deploy/gitea -n gitea --tail=50
# >>> restart the outside dependency (now pointed at 10.2.0.122) <<<
```
### Phase 6 — Cleanup (after a few days green; KEEP old PVC as rollback first)
```bash
kubectl delete sts postgres -n database --cascade=orphan # orphan keeps pods/PVC for rollback
kubectl delete svc postgres-hetzner -n database # temp restore svc
# DO NOT delete PVC postgres-data-postgres-0 yet — rollback safety net (~1 week)
# After confidence period:
kubectl delete pod -n database -l app=postgres # leftover orphan pod
kubectl delete pvc postgres-data-postgres-0 -n database
```
---
## Rollback (if Phase 4/5 fails — recovers OLD DB)
> **Caveat:** rollback loses any writes made to the new DB after cutover (old PVC was not updated by dump/restore). This is inherent to logical dump/restore migration. If you need zero-data-loss rollback, the migration must use logical replication instead — request that redesign separately.
```bash
# Repoint both Services back to old pods
kubectl patch svc postgres -n database --type=json \
-p='[{"op":"replace","path":"/spec/selector","value":{"app":"postgres"}}]'
kubectl patch svc postgres-service -n database --type=json \
-p='[{"op":"replace","path":"/spec/selector","value":{"app":"postgres"}}]'
# Scale consumers back up — they hit old DB again
kubectl scale deploy/immich-server -n immich --replicas=1
kubectl scale deploy/immich-machine-learning -n immich --replicas=1
kubectl scale deploy/gitea -n gitea --replicas=1
kubectl scale deploy/grafana -n monitoring --replicas=1
# >>> restart the outside dependency (pointed at 10.2.0.122) <<<
```
If rollback happens **before** Phase 6 cleanup, the old STS + PVC `postgres-data-postgres-0` are intact and the old DB serves immediately. If rollback happens **after** `kubectl delete sts postgres --cascade=orphan`, recreate the STS from `PostgreSQL/postgress_deplay.yaml` (the orphan pod + PVC are reused because the STS name + selector match).
---
## Pre-migration checklist (outside dependency)
Before starting Phase 1, ensure:
- [ ] **Outside dependency DB host updated from `10.0.2.116` → `10.2.0.122`** (the old pod IP is gone; the LB IP `10.2.0.122` is stable and routes to the new DB).
- [ ] Outside dependency that writes to `homeassistant` DB via `10.2.0.122` can be stopped for the maintenance window.
- [ ] Backup of any critical external state taken.
- [ ] Maintenance window scheduled.
## Pre-migration checklist (cluster)
- [ ] `kubectl get pvc -n database` shows `postgres-data-postgres-0` Bound on `local-storage`.
- [ ] `postgres-service` LB external IP is `10.2.0.122`.
- [ ] All consumer Deployments exist and are Ready (immich-server, immich-machine-learning, gitea, grafana).
- [ ] No `postgres-hetzner` Deployment/PVC exist yet.
@@ -0,0 +1,60 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-hetzner-config
namespace: database
data:
postgresql.conf: |
# PostgreSQL configuration file
# Managed via Kubernetes ConfigMap (PostgreSQL/hetzner/postgres_configmap.yaml)
# Edit here, then: kubectl apply -f postgres_configmap.yaml
# Restart the Deployment to pick up changes: kubectl rollout restart deploy/postgres-hetzner -n database
# -----------------------------
# Connection settings
# -----------------------------
listen_addresses = '*'
port = 5432
max_connections = 100
# -----------------------------
# Memory / resource tuning
# -----------------------------
shared_buffers = 512MB
work_mem = 16MB
maintenance_work_mem = 256MB
effective_cache_size = 4GB
# -----------------------------
# WAL / replication
# -----------------------------
wal_level = replica
max_wal_size = 4GB
min_wal_size = 128MB
checkpoint_completion_target = 0.9
# -----------------------------
# Query planner
# -----------------------------
random_page_cost = 1.1
effective_io_concurrency = 200
# -----------------------------
# Autovacuum
# -----------------------------
autovacuum_max_workers = 3
autovacuum_naptime = 60s
# -----------------------------
# Logging
# -----------------------------
log_destination = 'stderr'
logging_collector = off
log_min_duration_statement = -1
log_connections = off
log_disconnections = off
# -----------------------------
# Extensions (pgvector)
# -----------------------------
shared_preload_libraries = ''
@@ -15,13 +15,21 @@ spec:
labels:
app: postgres-hetzner
spec:
imagePullSecrets:
- name: registry-creds
containers:
- name: postgres
image: pgvector/pgvector:pg18-trixie
imagePullPolicy: IfNotPresent
image: rg.mariushome.lt/custom-postgres
imagePullPolicy: Always
args:
- -c
- config_file=/etc/postgresql/postgresql.conf
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql
- name: postgres-config
mountPath: /etc/postgresql
readOnly: true
env:
- name: POSTGRES_PASSWORD
valueFrom:
@@ -37,3 +45,6 @@ spec:
- name: postgres-data
persistentVolumeClaim:
claimName: postgres-hetzner-pvc
- name: postgres-config
configMap:
name: postgres-hetzner-config
+1 -1
View File
@@ -8,5 +8,5 @@ spec:
- ReadWriteOnce
resources:
requests:
storage: 39Gi
storage: 50Gi
storageClassName: hcloud-volumes
-17
View File
@@ -1,17 +0,0 @@
apiVersion: v1
kind: Service
metadata:
name: postgres-service
namespace: database
labels:
io.cilium/static-ip: "true"
annotations:
lbipam.cilium.io/ips: "10.2.0.122"
spec:
type: LoadBalancer
selector:
app: postgres-hetzner
ports:
- protocol: TCP
port: 5432
targetPort: 5432
-12
View File
@@ -1,12 +0,0 @@
apiVersion: v1
kind: Service
metadata:
name: postgres
namespace: database
spec:
selector:
app: postgres-hetzner
ports:
- protocol: TCP
port: 5432
targetPort: 5432
-38
View File
@@ -1,38 +0,0 @@
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
namespace: database
spec:
replicas: 1
serviceName: postgres
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: pgvector/pgvector:pg18-trixie
imagePullPolicy: IfNotPresent
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql
env:
- name: POSTGRES_PASSWORD
value: "jd@wXseh9z7vM@9"
- name: POSTGRES_USER
value: admin
volumeClaimTemplates:
- metadata:
name: postgres-data
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 30Gi
storageClassName: local-storage
+38 -1
View File
@@ -8,7 +8,7 @@ homelab cluster.
| Directory | Description |
|------------------|---------------------------------------------------------------|
| `Cilium/` | Cilium networking: `LoadBalancerIPPool`, `L2AnnouncementPolicy`, Ingress examples |
| `Cluster_admin/` | Admin notes: node restart commands, data migration examples |
| `Cluster_admin/` | Admin notes: node restart commands, firewall/egress, data migration examples |
| `DockerRegistry/`| Private Docker registry deployment, service, PVC and UI |
| `Gitea/` | Gitea deployment, service, ingress, namespace, PVC, DB secret |
| `Immich/` | Immich server, machine-learning, redis, config, secret |
@@ -69,3 +69,40 @@ points at `prometheus-operated.monitoring.svc.cluster.local:9090`).
--docker-email=<email>
```
- Review every manifest before applying it to a production cluster.
## Private registry authentication
`rg.mariushome.lt` requires htpasswd auth. Two out-of-band secrets must be
created before applying `DockerRegistry/docker_registry_deploy.yaml` and any
workload pulling from the registry (e.g. `postgres-hetzner`).
1. **Registry htpasswd file** (consumed by the registry pod). Generate the
htpasswd entry, then create the Secret in the `registry` namespace:
```bash
htpasswd -Bbn <user> <password> > htpasswd
kubectl create secret generic registry-htpasswd \
--namespace=registry \
--from-file=htpasswd=htpasswd
rm htpasswd
```
The deployment mounts this Secret at `/etc/docker/registry/htpasswd` and
configures the registry with `REGISTRY_AUTH=htpasswd`.
2. **`registry-creds` imagePullSecret** — one per namespace that pulls from
`rg.mariushome.lt`. Create it in every namespace that runs workloads
referencing the registry (e.g. `database`):
```bash
kubectl create secret docker-registry registry-creds \
--namespace=<ns> \
--docker-server=rg.mariushome.lt \
--docker-username=<user> \
--docker-password=<password> \
--docker-email=<email>
```
Manifests reference it as `imagePullSecrets: [{ name: registry-creds }]`.
Rebuild/repush the image per `Docker/PostgreSQL/PostgreSQL_Build.sh` after
rotating credentials.
+2 -1
View File
@@ -18,7 +18,8 @@ spec:
- gid=1001
- noperm
- mfsymlinks
- cache=strict
- cache=loose # mount.cifs defaults to strict when omitted; loose gives best single-stream perf on the throttled storagebox. Valid values: strict|none|loose (not "weak")
- actimeo=30 # default is 1s; raising it cuts stat roundtrips when listing directories
- noserverino # required to prevent data corruption
csi:
driver: smb.csi.k8s.io