Compare commits

..

5 Commits

11 changed files with 424 additions and 309 deletions
+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.
+1 -1
View File
@@ -10,7 +10,7 @@ RUN apt-get update && apt-get install -y \
python3-pip \ python3-pip \
python3-psycopg2 \ python3-psycopg2 \
rclone \ rclone \
&& git clone --branch v0.8.2 https://github.com/pgvector/pgvector.git \ && git clone --branch v0.8.4 https://github.com/pgvector/pgvector.git \
&& cd pgvector \ && cd pgvector \
&& make \ && make \
&& make install \ && make install \
+180
View File
@@ -0,0 +1,180 @@
# 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 / security group**: ensure ports 25, 465, 587,
143, 993, 4190 are open to the internet for the node(s) running the
`front` pod. Hetzner blocks outbound 25 by default for new accounts —
confirm it has been lifted (already done per planning).
## 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
-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.
-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
@@ -20,7 +20,7 @@ spec:
containers: containers:
- name: postgres - name: postgres
image: rg.mariushome.lt/custom-postgres image: rg.mariushome.lt/custom-postgres
imagePullPolicy: IfNotPresent imagePullPolicy: Always
args: args:
- -c - -c
- config_file=/etc/postgresql/postgresql.conf - config_file=/etc/postgresql/postgresql.conf