免費開始
營運指南 Hetzner · netcup · STRATO · 截至 2026 年 11 月 2 日

nextxch 跨多家供應商實現高可用性

當整個服務供應商離線時,郵件應維持順暢傳遞:無需昂貴的 Anycast、無需企業級負載平衡器,可從 Git 部署。本指南展示在 Hetzner、netcup 與 STRATO 的低成本伺服器上的三種設定,逐秒說明故障期間發生的情況,並計算資源與成本。每項服務供應商的宣告皆連結至註明檢查日期的來源,每項 nextxch 的宣告皆點名程式碼中的原始檔案。

01 · nextxch 為高可用性提供的功能(已在程式碼中驗證)

nextxch 支援主動-主動(active-active)架構:每個節點皆接受 SMTP、IMAP、JMAP、ActiveSync 與 HTTPS,沒有被動節點,也沒有黏性工作階段(sticky session)。PostgreSQL 維持共用狀態,郵件本身則以 SHA-256 定址的 .eml 物件存放在 Blob 儲存體中。

功能方式程式碼中的來源
無需 Redis 的叢集背板PostgreSQL LISTEN/NOTIFY(通道 nextxch_cluster_events)用於新郵件、旗標、expunge、佇列等事件;UNLOGGED 資料表 cluster_ephemeral 與 cluster_nodes;每 15 秒發送一次心跳,節點 60 秒無心跳即被移除src/Nextxch.Storage/Cluster/PostgresClusterCoordinator.cs
Leader 任務pg_try_advisory_lock:僅由一個節點續訂 ACME 憑證、發送授權心跳、同步 LDAP、發送行事曆提醒AcmeCertificateManager.cs, ClusterLicenseService.cs, LdapSyncService.cs, CalendarReminderPushService.cs
跨節點的 SMTP 佇列FOR UPDATE SKIP LOCKED:每個節點宣告不同的佇列項目,不會重複投遞src/Nextxch.Storage/Postgres/PostgresMailStore.cs
支援叢集的資料庫PostgreSQL(叢集預設)與 SQL Server (sp_getapplock);SQLite 僅限單一節點src/Nextxch.Storage/StorageServiceCollectionExtensions.cs
Blob 儲存區FileSystem、S3(具備 Content-MD5 的自訂 SigV4 用戶端)或混合式(本機 NVMe 快取 + S3)。物件鎖定模式:正常、治理、合規與法律保留src/Nextxch.Storage/Blobs/S3BlobStore.cs, HybridBlobStore.cs
憑證與 DKIMACME 憑證和 DKIM 金鑰存放在資料庫中;HTTP-01 挑戰在整個叢集內共用,任何節點都能應答;續期時保留葉憑證密鑰(DANE 3 1 1 保持有效)src/Nextxch.Security/Tls/AcmeCertificateManager.cs
健康檢查端點/health/live(不含資料庫)、/health/ready(資料庫可連線,否則回傳 503)、/health(概覽,含叢集對等節點)src/Nextxch.Server/Program.cs
真實用戶端 IPSMTP、IMAP、ManageSieve 的 PROXY 協議 v1/v2(Cluster:EnableProxyProtocol),以及來自 TrustedProxyCidrs 的 HTTP X-Forwarded-Forsrc/Nextxch.Core/Abstractions/IClusterCoordinator.cs
部署產物docker-compose.yml、Kubernetes 清單(3 個複本、HPA 2 至 10、PDB、探針)、Helm chart、deb/rpm、Windows MSIdeploy/kubernetes/, deploy/helm/nextxch/, deploy/packages/
授權按活動信箱計數,而非節點或 Pod;授權狀態透過 cluster_kv 共用src/Nextxch.Server/Services/ClusterLicenseService.cs, 價格方案

每個節點的連接埠:25、465、587 (SMTP),143、993 (IMAP),4190 (ManageSieve),80/443(HTTPS、ACME、Webmail、ActiveSync、JMAP)。POP3 110/995 預設關閉(Pop3Settings.cs 中的 Pop3:Enabled=false)。

唯一的硬性要求
所有節點在任何時候都需要恰好一個可寫入的 PostgreSQL 主節點和一個共用的 Blob 儲存體。如果資料庫無法存取,/health/ready 傳回 503 且節點無法驗證收件者。因此,跨服務供應商的高可用性意味著在各站點之間複製 PostgreSQL 和 Blob 儲存體並自動切換。這正是這三種設定所建構的。

02 · 讓高可用性變得簡單的郵件專屬規則

入站:MX 內建容錯移轉

寄件者會根據偏好排序 MX 記錄,且必須嘗試每個位址;當偏好相同時,他們必須隨機排序。[1]若目標無法連線,重試間隔應至少 30 分鐘,放棄時間應至少 4 至 5 天。[1]

出站:每個 IP 的 SPF 和 PTR

SPF 必須列出每個站台的每個出站 IP;ip4/ip6 不計入 10 次 DNS 查詢的限制。[2] Gmail 要求有效的正向和反向 DNS;PTR 需在每個服務商處分別設定。[8][14][27][31]

DKIM、MTA-STS、DANE

DKIM 金鑰存放在叢集資料庫中,一套 DNS 記錄服務所有節點;選取器允許多個金鑰並行。[3] MTA-STS 策略必須列出每一個 MX 主機;萬用字元僅涵蓋最左側的標籤。[4] DANE 需要每個 MX 主機有一筆 TLSA 記錄,建議使用 3 1 1,且網域必須經 DNSSEC 簽署。[5]

客戶端:IMAP、提交、HTTPS

郵件用戶端沒有類似 MX 的容錯移轉機制。它們連線到一個名稱(此處為 mail.example.com),其 A 記錄由健康檢查作業維護。IDLE 連線至少每 29 分鐘重新發起一次,隨後會落到健康的節點上。[7][6]

兩個站台的 DNS 區域(範本)
; Zone example.com (TTL in seconds). IPs are documentation ranges: replace them.
; Site A = Hetzner 192.0.2.10, site B = netcup 198.51.100.20, site C (medium setup) = 203.0.113.30

; Inbound SMTP: equal preference, senders MUST randomize (RFC 5321 section 5.1).
example.com.            3600 IN MX 10 mx1.example.com.
example.com.            3600 IN MX 10 mx2.example.com.

; Static per-site names: never touched by the failover job (stable FCrDNS for PTR).
mx1.example.com.        3600 IN A     192.0.2.10
mx2.example.com.        3600 IN A     198.51.100.20

; Client name (IMAP, submission, HTTPS, webmail, ActiveSync, autodiscover):
; short TTL, kept up to date by the health-check job. Start with all healthy nodes.
mail.example.com.         60 IN A     192.0.2.10
mail.example.com.         60 IN A     198.51.100.20

; SPF: every outbound IP of every site. ip4/ip6 do not count against the 10-lookup limit (RFC 7208 4.6.4).
example.com.            3600 IN TXT   "v=spf1 ip4:192.0.2.10 ip4:198.51.100.20 ip4:203.0.113.30 -all"

; DKIM: nextxch keeps the keys in the cluster database, so one record set serves all nodes.
; Publish the selectors shown under /admin/ (Domains > DKIM).

; MTA-STS: the policy must list every MX host (see the note on gaps).
_mta-sts.example.com.   3600 IN TXT   "v=STSv1; id=20261102"

; DANE (optional, needs a DNSSEC-signed zone): one TLSA record per MX host.
; nextxch reuses the leaf key on renewal, so "3 1 1" stays stable.
_25._tcp.mx1.example.com. 3600 IN TLSA 3 1 1 <sha256-of-spki>
_25._tcp.mx2.example.com. 3600 IN TLSA 3 1 1 <sha256-of-spki>

; PTR (set in the provider console, not in this zone):
;   192.0.2.10    -> mx1.example.com   (Hetzner Console / Robot)
;   198.51.100.20 -> mx2.example.com   (netcup SCP)
EHLO 名稱與 PTR
伺服器主機名稱(mail.example.com,用於客戶端、autodiscover 與憑證)在整個叢集範圍內生效。每個節點設定自己的 EHLO/HELO 名稱:在設定中設定 Smtp:HeloHostname,或在 /admin/ 的「主機名稱、IPv6 & 連接埠」下設定(每個節點的 EHLO 名稱,並按節點進行 PTR 檢查)。該名稱用於 220 歡迎橫幅、EHLO 回應與出站 EHLO。請將每個 IP 的 PTR 指向其固定名稱 mx1/mx2;DNS 顧問會為每個節點顯示一條 HELO SPF 記錄。此外,RFC 5321 第 4.1.4 節禁止僅因 EHLO 名稱不匹配而拒收郵件。[1][8]
每個節點的 EHLO 名稱
# appsettings.Production.json per node (or admin: Hostname, IPv6 & Ports > EHLO name per node)
# Site A (Hetzner):
{ "Smtp": { "ServerHostName": "mail.example.com", "HeloHostname": "mx1.example.com" } }
# Site B (netcup):
{ "Smtp": { "ServerHostName": "mail.example.com", "HeloHostname": "mx2.example.com" } }
# PTR 192.0.2.10 -> mx1.example.com, PTR 198.51.100.20 -> mx2.example.com
包含所有 MX 主機的 MTA-STS 政策(由 nextxch 按網域提供)
# Served by nextxch itself at https://mta-sts.example.com/.well-known/mta-sts.txt
# (admin: Domains > domain > Transport > MTA-STS). Empty MX list = automatic:
# the domain's MX records from DNS + server host name + EHLO names of all nodes.
# Wildcards like *.example.com are allowed. Every change changes the policy id;
# the DNS advisor shows the matching _mta-sts TXT record.
version: STSv1
mode: enforce
mx: mx1.example.com
mx: mx2.example.com
max_age: 604800

03 · 用戶端重新導向方式:方案比較

服務商的容錯移轉 IP 僅在單一服務商內部有效。若整個服務商發生故障,DNS 仍是簡單且低成本的工具。

選項範圍成本評估
多個優先權相同的 MX跨服務商0 €入站郵件必要,已標準化 [1]
自有健康檢查作業 + DNS API (Cloudflare、Hetzner、deSEC、netcup)跨服務商0 €建議。Cloudflare:TTL 從 60 秒(Enterprise 30 秒)起,自動 = 300 秒。Hetzner DNS:免費,TTL 從 60 秒起,API 位於 Hetzner 主控台中。deSEC:每個網域最低 TTL,例如 3600 秒,僅限應要求調低。netcup:存在 CCP DNS API,未記錄最低 TTL。[38][39][21][40][29]
Cloudflare 負載平衡(僅 DNS)跨服務商每月 USD 5 起Enterprise 方案以外每 15 秒執行一次健康檢查(含 TCP、SMTP);A/AAAA/CNAME 可用,MX/SRV 僅限 Enterprise。可取代 mail.example.com 的專屬作業。[33][34][35][36]
Cloudflare Spectrum跨服務商Enterprise任意 TCP 連接埠(25、465、587、993)僅作為 Enterprise 附加元件提供;Pro/Business 僅支援 SSH、Minecraft、RDP。[37]
Hetzner Floating IP (Cloud)一個專案,一個網路區域IPv4 €3.00,IPv6 €1.00/月僅限 Hetzner 內部 [9]
Hetzner 容錯移轉 IP(Robot,獨立伺服器)Hetzner 資料中心€4.20/月 + €4.90 設定費透過 Robot API 在 90 至 110 秒內切換,僅限 Hetzner 內部 [11]
netcup 備援 IP同一 netcup 機房€5.00/月,含增值稅可隨時在 SCP 中免費重新路由,僅限 netcup 內部 [24][25]
Akamai/Linode IP 共用一個資料中心,兩台 LinodeUSD 5 起(Nanode)基於 BGP (lelastic),僅限同一資料中心;NodeBalancer Basic USD 10、TCP/HTTP [41][42]
Anycast / 自有 BGP全域高自有 ASN(透過成員資格或贊助 LIR 的 RIPE 合約)以及自有位址空間(在 Vultr 至少 /24 IPv4 或 /48 IPv6)。對於多數 nextxch 部署而言不符合比例原則。[43][44]
為什麼需要見證節點
只有兩個端點時,任何一方都無法判斷對方是故障了還是僅僅連線中斷。如果雙方都把自己提升為主節點,就會產生兩個分歧的資料庫(腦裂)。etcd 按多數決決定:三個成員中有兩個即可。因此:在三家服務商處設定三票,其中第三票可以是小型見證節點。[48][53]

04 · 設定 S:雙站點加見證節點

適用於中小型企業。站台 A(例如 Hetzner Cloud)與站台 B(例如 netcup VPS)各自執行 nextxch、由 Patroni 管理的 PostgreSQL、一個 etcd 成員與一個 Garage 區域。位於第三家服務商(例如 STRATO)的小型見證節點 C 承載第三個 etcd 成員、第三份 Garage 副本以及 DNS 容錯移轉檢查程式。三者之間透過 WireGuard 組成網狀互連。

flowchart TB
  U["Users: IMAP, SMTP submission, HTTPS"] -->|"mail.example.com TTL 60"| DNS["DNS with health-check job"]
  S["Remote mail servers"] -->|"MX 10 mx1 / MX 10 mx2"| A1
  S --> B1
  DNS --> A1
  DNS --> B1
  subgraph A["Site A: Hetzner"]
    A1["nextxch"] --> AP[("PostgreSQL primary")]
    A1 --> AG["Garage zone A"]
    AE["etcd"]
  end
  subgraph B["Site B: netcup"]
    B1["nextxch"] --> BP[("PostgreSQL replica")]
    B1 --> BG["Garage zone B"]
    BE["etcd"]
  end
  subgraph C["Witness C: STRATO"]
    CE["etcd"]
    CG["Garage zone C"]
    CF["Failover checker"]
  end
  B1 -.->|"WireGuard"| AP
  AP ==>|"synchronous replication"| BP
  AG <-.-> BG
  BG <-.-> CG
  AE <-.-> BE
  BE <-.-> CE
架構配置 S

為什麼選擇 Garage 作為 blob 儲存區?

單一供應商處的 S3 儲存貯體將隨著該供應商消失,且 nextxch 目前只能寫入一個 S3 目標。Garage 是一個相容 S3 的儲存體(AGPL-3.0),專為透過網域連接的多個資料中心而建置(專案要求:最多 200 毫秒延遲,至少 50 Mbit/s)。在 replication_factor = 3 的情況下,每個區域有一份複本;只要只有一個區域故障,讀寫就會繼續(寫入法定人數為 2)。若只有兩個區域,失去一個區域會使儲存體變為唯讀,這就是為什麼見證節點也持有完整複本。[60][61]

未經測試,且無 Object Lock
Garage 既不支援 S3 Object Lock,也不支援版本控制。啟用 WORM 保留 (governance/compliance) 的網域會使 nextxch 發送保留標頭,因此需要支援 Object Lock 的 S3;GoBD 副本請參見第 09 章。本指南未對在 Garage 上執行 nextxch 進行負載測試:投入生產前請先用測試資料驗證。[62]

分步說明

  1. 訂購伺服器:A = Hetzner Cloud(連接埠 25/465 預設被封鎖;滿一個月且首張帳單付款後可申請解封,587 開放),B = netcup VPS(在 SCP 中移除防火牆策略 "netcup Mail block"),C = STRATO VPS 作為見證節點(見證節點不需要連接埠 25)。[13][26]
  2. 設定 PTR:IP A 指向 mx1.example.com(Hetzner Console),IP B 指向 mx2.example.com(netcup SCP)。[14][27]
  3. 透過 cloud-init 進行基礎安裝(Debian 13):部署使用者、Docker、WireGuard,禁止密碼登入。
  4. A、B、C 之間的 WireGuard 網狀網路 10.88.0.0/24;僅對對端 IP 開放 UDP 51820。[47]
  5. 三個站點都執行 etcd(選舉逾時至少為 10 × RTT),然後在 A 和 B 上執行 Patroni + PostgreSQL 18。[50][53]
  6. 在所有三個伺服器上部署 Garage,套用包含三個區域的佈局,並建立儲存桶與金鑰。[61]"}]}}
  7. 在 A 和 B 上透過 Docker Compose 執行 nextxch(Cluster:Enabled=true、多主機連線字串、S3 指向本地 Garage)。在 /admin/ 中設定主機名稱 mail.example.com,並為 mail、mx1、mx2 簽發 ACME 憑證。
  8. 按第 02 章設定 DNS,在 /admin/ 中檢查 MTA-STS MX 清單,並在 /admin/ 的「網域」下啟用 DNS 容錯移轉(僅叢集主節點執行),或者改用在 etcd 鎖定下執行的指令碼。
  9. 按第 09 章進行備份並測試還原。接著排練一次故障:強制停止網站 A 並遵循第 08 章。
cloud-init(使用者資料)
#cloud-config
# Hetzner Cloud / netcup: paste as user data when creating the VM.
users:
  - name: deploy
    groups: [sudo, docker]
    shell: /bin/bash
    sudo: "ALL=(ALL) NOPASSWD:ALL"
    ssh_authorized_keys:
      - ssh-ed25519 AAAA... ci-deploy
package_update: true
packages: [wireguard, curl, jq, docker.io, docker-compose-v2, unattended-upgrades]
runcmd:
  - [ systemctl, enable, --now, docker ]
  - [ sed, -i, "s/^#\\?PasswordAuthentication.*/PasswordAuthentication no/", /etc/ssh/sshd_config ]
  - [ systemctl, restart, ssh ]
WireGuard:/etc/wireguard/wg0.conf
# /etc/wireguard/wg0.conf on site A (Hetzner). Same pattern on B and C.
# Full mesh: every site has one [Peer] block per other site.
[Interface]
Address    = 10.88.0.1/24
ListenPort = 51820
PrivateKey = <private-key-of-site-A>   # wg genkey, never commit it

[Peer]  # site B (netcup)
PublicKey           = <public-key-of-site-B>
Endpoint            = 198.51.100.20:51820
AllowedIPs          = 10.88.0.2/32
PersistentKeepalive = 25

[Peer]  # site C (witness or third site)
PublicKey           = <public-key-of-site-C>
Endpoint            = 203.0.113.30:51820
AllowedIPs          = 10.88.0.3/32
PersistentKeepalive = 25

# systemctl enable --now wg-quick@wg0
# Firewall: UDP 51820 open only for the two peer IPs.
etcd:/etc/default/etcd
# /etc/default/etcd on site A (Debian package etcd-server). Sites B and C analogue.
# Three members = quorum of two: any single site may fail.
ETCD_NAME="site-a"
ETCD_DATA_DIR="/var/lib/etcd/default"
ETCD_LISTEN_PEER_URLS="http://10.88.0.1:2380"
ETCD_LISTEN_CLIENT_URLS="http://10.88.0.1:2379,http://127.0.0.1:2379"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://10.88.0.1:2380"
ETCD_ADVERTISE_CLIENT_URLS="http://10.88.0.1:2379"
ETCD_INITIAL_CLUSTER="site-a=http://10.88.0.1:2380,site-b=http://10.88.0.2:2380,site-c=http://10.88.0.3:2380"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_INITIAL_CLUSTER_TOKEN="nextxch-ha"
# WAN tuning (etcd tuning guide: election timeout at least 10x the round trip).
# Example for up to ~25 ms RTT between providers:
ETCD_HEARTBEAT_INTERVAL="250"
ETCD_ELECTION_TIMEOUT="2500"
# Traffic stays inside WireGuard. For production add TLS (ETCD_CERT_FILE etc.).
Patroni:/etc/patroni/config.yml
# /etc/patroni/config.yml on site A (Debian/PGDG package "patroni").
# Site B: name/addresses analogue. The witness C runs etcd only, no PostgreSQL.
scope: nextxch
name: pg-site-a

restapi:
  listen: 10.88.0.1:8008
  connect_address: 10.88.0.1:8008

etcd3:
  hosts: 10.88.0.1:2379,10.88.0.2:2379,10.88.0.3:2379

bootstrap:
  dcs:
    ttl: 30                 # defaults; rule: loop_wait + 2 * retry_timeout <= ttl
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    synchronous_mode: on    # a 250 OK to a sender is only given after the commit reached a 2nd site
    synchronous_mode_strict: false   # if the replica site is gone, keep accepting mail (falls back to async)
    failsafe_mode: true
    postgresql:
      use_pg_rewind: true
      parameters:
        wal_level: replica
        hot_standby: "on"
        max_wal_senders: 10
        max_replication_slots: 10
        wal_log_hints: "on"
        archive_mode: "on"
        archive_command: "pgbackrest --stanza=nextxch archive-push %p"
  initdb: [ {encoding: UTF8}, data-checksums ]

postgresql:
  listen: 10.88.0.1:5432
  connect_address: 10.88.0.1:5432
  data_dir: /var/lib/postgresql/18/main
  bin_dir: /usr/lib/postgresql/18/bin
  authentication:
    replication: { username: replicator, password: "${PATRONI_REPLICATION_PASSWORD}" }
    superuser:   { username: postgres,   password: "${PATRONI_SUPERUSER_PASSWORD}" }
  pg_hba:
    - host replication replicator 10.88.0.0/24 scram-sha-256
    - host nextxch     nextxch    10.88.0.0/24 scram-sha-256
Garage:/etc/garage.toml
# /etc/garage.toml, identical on all three sites except rpc_public_addr.
metadata_dir = "/var/lib/garage/meta"
data_dir     = "/var/lib/garage/data"
db_engine    = "lmdb"

replication_factor = 3          # one copy per zone (site); writes need 2 of 3
consistency_mode   = "consistent"

rpc_bind_addr   = "10.88.0.1:3901"
rpc_public_addr = "10.88.0.1:3901"
rpc_secret      = "<openssl rand -hex 32, same on all nodes>"

[s3_api]
s3_region     = "garage"
api_bind_addr = "127.0.0.1:3900"   # each nextxch node talks to its local Garage

# After the first start (node ids from `garage node id`):
#   garage layout assign <id-a> -z hetzner -c 500G
#   garage layout assign <id-b> -z netcup  -c 500G
#   garage layout assign <id-c> -z witness -c 500G
#   garage layout show && garage layout apply --version 1
#   garage bucket create nextxch
#   garage key create nextxch-app
#   garage bucket allow --read --write --owner nextxch --key nextxch-app
nextxch: 每個站台一個 docker-compose.yml
# docker-compose.yml on site A and site B (nextxch only; PostgreSQL/Patroni, etcd,
# Garage and WireGuard run as system services on the same VM).
# Secrets come from .env (never committed): NEXTXCH_LICENSE, PG_PASSWORD, S3_KEY, S3_SECRET
name: nextxch

services:
  nextxch:
    image: nextxch/server:${NEXTXCH_TAG}
    restart: unless-stopped
    network_mode: host            # real client IPs for SPF/DMARC, direct WireGuard reach
    environment:
      ASPNETCORE_URLS: "http://*:80;https://*:443"
      License__Token: "${NEXTXCH_LICENSE}"
      Cluster__Enabled: "true"
      Cluster__NodeId: "${SITE_NAME}"          # hetzner-a / netcup-b
      Storage__Provider: "Postgres"
      # Npgsql multi-host: always connects to the current Patroni primary
      Storage__PostgresConnectionString: "Host=10.88.0.1,10.88.0.2;Port=5432;Database=nextxch;Username=nextxch;Password=${PG_PASSWORD};Target Session Attributes=primary;Host Recheck Seconds=5"
      Storage__BlobBackend: "S3"
      Storage__Compression: "Zstd"
      Storage__S3__EndpointUrl: "http://127.0.0.1:3900"
      Storage__S3__Region: "garage"
      Storage__S3__BucketName: "nextxch"
      Storage__S3__ForcePathStyle: "true"
      Storage__S3__AccessKey: "${S3_KEY}"
      Storage__S3__SecretKey: "${S3_SECRET}"
      Smtp__ServerHostName: "mail.example.com"
      Imap__ServerHostName: "mail.example.com"
      ManageSieve__ServerHostName: "mail.example.com"
      Acme__Enabled: "true"
      Acme__ContactEmail: "postmaster@example.com"
    volumes:
      - nextxch-data:/app/data
    healthcheck:
      test: ["CMD", "curl", "-fsS", "http://127.0.0.1/health/ready"]
      interval: 15s
      timeout: 5s
      retries: 3

volumes:
  nextxch-data:

連接字串指定兩個帶有 Target Session Attributes=primary 的 PostgreSQL 主機。nextxch 透過 NpgsqlDataSource.Create (PostgresMailStore.cs) 建立連線;有多個主機時,Npgsql 會自動建構多主機資料來源,且只連線到目前的primary,每隔 Host Recheck Seconds(預設 10 秒)重新檢查狀態。Patroni 容錯移轉後,節點無需任何設定變更即可重新連線;叢集 LISTEN 連線每 2 秒重試一次 (PostgresClusterCoordinator.cs)。[63]

mail.example.com 的自動 DNS 容錯移轉

nextxch 內建 DNS 容災備援代理程式(選用,預設關閉;位於 /admin/ 的網域下,卡片「DNS failover」)。每個節點每 30 秒透過其公開 IP 檢查所有節點在連接埠 25 上的 SMTP 橫幅以及 HTTPS /health。只有叢集領導節點會執行動作:它持有 PostgreSQL advisory lock,透過多數決結合所有節點的檢視,並透過 Hetzner DNS (Cloud API) 或 Cloudflare API 寫入所設定名稱的 A/AAAA 記錄。遲滯:經過 N 次失敗輪次後節點離開 DNS,經過 M 次健康輪次後返回;最後一個節點絕對不會被移除。每次變更皆記錄在事件記錄檔中,告警規則「DNS failover: node taken out」會透過維運告警發出通知。API 權杖以伺服器金鑰環加密,且絕不會再次顯示。

內建 DNS 故障轉移代理程式
# Admin: Domains > DNS failover (cluster). Stored cluster-wide; the token is encrypted
# with the server keyring and never shown again. Equivalent settings:
Provider:          Hetzner DNS (Cloud API, api.hetzner.cloud)   | Cloudflare DNS
Zone:              example.com
Names:             mail.example.com            # A/AAAA follow the healthy nodes
TTL:               60                          # resolvers keep old answers this long
Interval:          30 s
Failures (N):      3                           # 3 x 30 s before a node leaves DNS
Successes (M):     5                           # 5 x 30 s before it returns
Checks:            SMTP 25 (220 banner), HTTPS /health
Nodes:             fsn1, 192.0.2.10, 2001:db8::10
                   nbg1, 198.51.100.20
# Alert: rule "DNS failover: node taken out" (Alerts) fires when a node is out of DNS.
為什麼被隔離的節點不會變更 DNS
leader 鎖只能透過與 PostgreSQL 主節點的連線獲得。在連線字串中設定 Target Session Attributes=primary(見上文第 04 章)後,被隔離的一方連不到主節點,拿不到鎖,保持被動。所有觀察者的多數投票可防止檢視異常的單一節點移除健康節點。

替代方案:在 etcd 鎖定下執行的指令碼

對於沒有內建連接器的 DNS 提供者(例如 deSEC),或當 etcd 應做出決定時,此指令碼仍然是等效的替代方案。請勿同時為相同名稱執行代理程式與指令碼。該指令碼每 20 秒透過其公用 IP 檢查每個節點的 /health/ready,並透過 Cloudflare API 協調 A 記錄(在 dns_records 上執行 PATCH/POST/DELETE)。它在每個站台上以 etcdctl lock 執行:只有一個複本會執行動作,且僅在具備 etcd 多數決的一側執行。因此,遭到切斷的站台將無法再變更 DNS。對於 Hetzner DNS 或 deSEC,只有三個 curl 呼叫會變更。[39]

nextxch-dns-failover.sh
#!/usr/bin/env bash
# /usr/local/bin/nextxch-dns-failover.sh
# ALTERNATIVE to the built-in agent (admin: Domains > DNS failover), e.g. for DNS
# providers without a built-in connector (deSEC) or when etcd decides anyway.
# Keeps the A records of mail.example.com equal to the set of healthy nodes.
# Runs on every site under an etcd lock, so only one copy acts, and only on the
# side that still has etcd quorum (a cut-off minority site can never change DNS).
#   ExecStart=etcdctl --endpoints=http://127.0.0.1:2379 lock nextxch-dns /usr/local/bin/nextxch-dns-failover.sh
# Needs: curl, jq. Secrets via systemd EnvironmentFile (CF_API_TOKEN, CF_ZONE_ID).
set -euo pipefail

NAME="mail.example.com"
TTL=60
NODES=("192.0.2.10" "198.51.100.20")     # public IPs of the nextxch nodes
FAILS_BEFORE_REMOVE=3                    # 3 x 20 s = 1 minute
STATE=/run/nextxch-failover; mkdir -p "$STATE"
API="https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records"
AUTH=(-H "Authorization: Bearer ${CF_API_TOKEN}" -H "Content-Type: application/json")

healthy() {   # HTTPS readiness through the public IP, with SNI for the real name
  curl -fsS --max-time 5 --resolve "${NAME}:443:$1" "https://${NAME}/health/ready" \
    | jq -e '.status == "ready"' >/dev/null
}

while true; do
  want=()
  for ip in "${NODES[@]}"; do
    f="$STATE/$ip"; n=$(cat "$f" 2>/dev/null || echo 0)
    if healthy "$ip"; then echo 0 > "$f"; want+=("$ip")
    else n=$((n+1)); echo "$n" > "$f"; [ "$n" -lt "$FAILS_BEFORE_REMOVE" ] && want+=("$ip"); fi
  done
  # Never publish an empty set: if everything looks down, the checker is probably the problem.
  [ "${#want[@]}" -eq 0 ] && { sleep 20; continue; }

  have=$(curl -fsS "${AUTH[@]}" "${API}?type=A&name=${NAME}" | jq -r '.result[] | "\(.id) \(.content)"')
  for ip in "${want[@]}"; do   # add missing healthy IPs
    grep -q " ${ip}$" <<<"$have" || curl -fsS "${AUTH[@]}" -X POST "$API" \
      --data "{\"type\":\"A\",\"name\":\"${NAME}\",\"content\":\"${ip}\",\"ttl\":${TTL},\"proxied\":false}" >/dev/null
  done
  while read -r id ip; do      # remove IPs that are no longer healthy
    [ -z "${id:-}" ] && continue
    printf '%s\n' "${want[@]}" | grep -qx "$ip" || curl -fsS "${AUTH[@]}" -X DELETE "${API}/${id}" >/dev/null
  done <<<"$have"
  sleep 20
done
systemd 單元
# /etc/systemd/system/nextxch-dns-failover.service (install on every site)
[Unit]
Description=nextxch DNS failover (runs only while holding the etcd lock)
After=network-online.target etcd.service wg-quick@wg0.service
Wants=network-online.target

[Service]
EnvironmentFile=/etc/nextxch/dns-failover.env
ExecStart=/usr/bin/etcdctl --endpoints=http://127.0.0.1:2379 lock nextxch-dns /usr/local/bin/nextxch-dns-failover.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

05 · 設定 M:三個完整站點(Proxmox 或一般虛擬機器)

與設定 S 類似,但三個站台皆執行帶有 PostgreSQL 複本的 nextxch。當一個站台故障時,仍保留兩個資料庫與兩個 nextxch 節點,且透過 synchronous_mode 甚至能維持同步複製。三筆具有相同優先順序的 MX 紀錄可分散入站負載。

flowchart TB
  S["Remote mail servers"] -->|"MX 10 mx1, mx2, mx3"| N
  U["Users"] -->|"mail.example.com"| N
  subgraph N["WireGuard mesh 10.88.0.0/24"]
    direction LR
    subgraph A["Hetzner"]
      A1["nextxch"] --- A2[("Patroni + PG")] --- A3["etcd + Garage"]
    end
    subgraph B["netcup"]
      B1["nextxch"] --- B2[("Patroni + PG")] --- B3["etcd + Garage"]
    end
    subgraph C["Third provider"]
      C1["nextxch"] --- C2[("Patroni + PG")] --- C3["etcd + Garage"]
    end
  end
  N --> BK["Backups: Storage Box + S3 at another provider"]
架構配置 M
Proxmox:不支援跨服務商叢集
根據 Proxmox 的說明,corosync 需要低於 5 ms 的延遲(區域網路級別);超過約 10 ms 且節點多於三個時,基本無法正常工作。因此不建議組建橫跨 Hetzner、netcup 和 STRATO 的單個 Proxmox VE 叢集。正確的模式是:每家服務商各有一台獨立的 Proxmox 主機或一個叢集,高可用由應用層提供(Patroni、Garage、nextxch 叢集)。QDevice (corosync-qnetd) 用於單站點的雙節點叢集,不受延遲限制。Proxmox Datacenter Manager(自 2025-12-04 起為 1.0 版)可統一管理多個叢集。[45]

分步說明

  1. 三家服務商的三台虛擬機器(或 Proxmox 客戶機),Debian 版本相同,PTR 分別指向 mx1/mx2/mx3。
  2. 包含三個主機的 Ansible Inventory,一個適用於全部的 Playbook(WireGuard、etcd、Patroni、Garage、nextxch)。
  3. 沿用方案 S 的 Patroni 設定並增加第三台主機;synchronous_mode: on,三個資料庫時短 quorum。[54]
  4. 包含三個主機的連線字串、包含三個區域的 Garage 佈局、三條 MX 記錄,SPF 和 DNS 容錯移轉節點列表中各有三個 IP。
  5. Proxmox Backup Server 可選用於虛擬機器映像:資料儲存位於本機或 S3(自 PBS 4.2 起官方支援 S3 後端);Proxmox 並未將透過 CIFS 掛載的 Storage Box 等網路共用列為資料儲存類型。[46]
Ansible:inventory/ha.yml
# inventory/ha.yml: three sites, one VM (or Proxmox guest) per site
all:
  vars:
    ansible_user: deploy
    wg_network: 10.88.0.0/24
    pg_major: 18
  children:
    nextxch_sites:
      hosts:
        hetzner-a: { ansible_host: 192.0.2.10,    wg_ip: 10.88.0.1, garage_zone: hetzner }
        netcup-b:  { ansible_host: 198.51.100.20, wg_ip: 10.88.0.2, garage_zone: netcup }
        third-c:   { ansible_host: 203.0.113.30,  wg_ip: 10.88.0.3, garage_zone: third }
Ansible:site.yml
# site.yml: idempotent base for every site (same playbook for Hetzner, netcup, Strato ...)
- hosts: nextxch_sites
  become: true
  tasks:
    - name: Base packages (Debian 13)
      ansible.builtin.apt:
        name: [wireguard, etcd-server, etcd-client, patroni, pgbackrest, docker.io, docker-compose-v2, jq, curl]
        update_cache: true
    # PostgreSQL 18 itself comes from the PGDG apt repository (apt.postgresql.org),
    # Garage as the static binary or the dxflrs/garage image.

    - name: WireGuard config
      ansible.builtin.template: { src: wg0.conf.j2, dest: /etc/wireguard/wg0.conf, mode: "0600" }
      notify: restart wg

    - name: etcd, Patroni and Garage config
      ansible.builtin.template: { src: "{{ item.src }}", dest: "{{ item.dest }}", mode: "0640" }
      loop:
        - { src: etcd.env.j2,     dest: /etc/default/etcd }
        - { src: patroni.yml.j2,  dest: /etc/patroni/config.yml }
        - { src: garage.toml.j2,  dest: /etc/garage.toml }

    - name: nextxch compose file
      ansible.builtin.template: { src: docker-compose.yml.j2, dest: /opt/nextxch/docker-compose.yml }

    - name: Start nextxch
      ansible.builtin.command: docker compose up -d
      args: { chdir: /opt/nextxch }
      changed_when: false

  handlers:
    - name: restart wg
      ansible.builtin.service: { name: wg-quick@wg0, state: restarted }

06 · 方案 L:在三家服務商上執行 Kubernetes

適用於大量信箱和水平擴充。首先要注意:k3s 明確不支援在跨雲分佈的叢集中使用內嵌 etcd;伺服器節點應位於同一地點。因此:每家服務商一個 Kubernetes 叢集(各用 k3s 或 Talos),每個叢集都執行基於隨附 Helm chart 的 nextxch 部署。資料層(Patroni + etcd + Garage)與配置 M 一樣透過 WireGuard 執行在獨立的虛擬機器上,由三個叢集共同使用。[49][48]

flowchart TB
  DNS["DNS: MX per provider LB, mail.example.com with health checks"]
  subgraph K1["k3s/Talos cluster Hetzner"]
    L1["Load balancer"] --> P1["nextxch pods (HPA)"]
  end
  subgraph K2["k3s/Talos cluster netcup"]
    L2["Load balancer"] --> P2["nextxch pods (HPA)"]
  end
  subgraph K3["k3s/Talos cluster STRATO"]
    L3["Load balancer"] --> P3["nextxch pods (HPA)"]
  end
  DNS --> L1
  DNS --> L2
  DNS --> L3
  subgraph D["Data layer on VMs, WireGuard"]
    PG[("Patroni: primary + 2 replicas")]
    GA["Garage: 3 zones"]
    ET["etcd: 3 members"]
  end
  P1 --> PG
  P2 --> PG
  P3 --> PG
  P1 --> GA
  P2 --> GA
  P3 --> GA
架構配置 L

為什麼不跨叢集使用 CloudNativePG?

CloudNativePG 可以在其他 Kubernetes 叢集中執行複本叢集,但叢集之間的升級與降級是宣告式的(欄位 primary、promotionToken),亦即非自動化。若要進行自動的提供者容錯移轉,跨三個站台使用 Patroni 搭配 etcd 是更直接的解決方案。[52]

一個叢集涵蓋所有服務商?

Talos 提供 KubeSpan(跨站點的 WireGuard 全網狀連線),k3s 提供 flannel 後端 wireguard-native。但控制平面 (etcd) 對廣域網延遲很敏感。多個小型叢集更易於維運,且各自獨立發生故障。[51][49][50]

分步說明

  1. 建置資料層,如安裝 M(三部虛擬機器執行 Patroni、etcd、Garage)。
  2. 每家服務商一個 k3s 或 Talos 叢集;透過 WireGuard(或 KubeSpan)與資料層建立網路連線。
  3. 入站連接埠:使用 LoadBalancer 類型的服務並設定 externalTrafficPolicy: Local(與存放庫中一致),以便為 SPF/DMARC 保留寄件者 IP;如果負載平衡器支援 PROXY protocol,請改用 Cluster__EnableProxyProtocol=true。Hetzner Cloud Load Balancer 支援 PROXY protocol 和任意 TCP 服務。[19]
  4. 出站連接埠 25:透過具有相符 PTR 和 SPF 條目的固定 IP 進行 Pod 封包出口(出口閘道,如 deploy/kubernetes/README.md 中所述)。
  5. 各供應商的 Helm values,透過管線依序部署(第 07 章)。HPA(CPU 達 70% 時 2 至 10 個 Pod)與 PodDisruptionBudget 隨存放庫提供。
Helm:k8s/values-hetzner.yaml
# values-hetzner.yaml (one file per provider cluster; netcup/strato analogue)
# Helm chart: deploy/helm/nextxch in the nextxch repository.
replicaCount: 3
mail:
  hostname: mail.example.com
  defaultDomain: example.com
postgres:
  # Patroni data layer outside Kubernetes, reached through WireGuard / KubeSpan
  connectionString: "Host=10.88.0.1,10.88.0.2,10.88.0.3;Database=nextxch;Username=nextxch;Password=<from secret>;Target Session Attributes=primary"
s3:
  endpointUrl: "http://garage.nextxch-data.svc:3900"   # Garage zone of this provider
  bucketName: "nextxch"

07 · 從 Git 部署與更新

所有重要內容皆為存放庫中的檔案:compose 檔案或 Helm values、Ansible 清單、DNS 容錯移轉指令碼。管線每次僅部署一個網站,並等待 /health/ready 再次回報 "ready" 後才會繼續。機密資訊(授權、密碼、API 權杖、SSH 金鑰)僅存放於 GitHub/GitLab 機密存放區或伺服器上的 .env 中,絕不存放在存放庫中。

flowchart TB
  G["git push to main"] --> V["Validate: compose config / helm lint"]
  V --> A["Roll out site A"]
  A --> HA{"/health/ready = ready?"}
  HA -->|"yes"| B["Roll out site B"]
  HA -->|"no"| X["Abort, B stays on old version"]
  B --> HB{"/health/ready = ready?"}
  HB -->|"yes"| C["Roll out site C"]
  HB -->|"no"| X
  C --> OK["Done"]
部署管線
GitHub Actions:Compose 站點
# .github/workflows/deploy.yml: rolling update of the compose sites, one site at a time.
name: deploy-nextxch
on:
  push:
    branches: [main]
    paths: ["sites/**", "compose/**"]
  workflow_dispatch:

concurrency: { group: deploy-nextxch, cancel-in-progress: false }

jobs:
  deploy:
    runs-on: ubuntu-latest
    strategy:
      max-parallel: 1            # never update two sites at once
      matrix:
        site: [hetzner-a, netcup-b]
    environment: ${{ matrix.site }}
    steps:
      - uses: actions/checkout@v4
      - name: Write SSH key
        run: |
          install -m 700 -d ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
          echo "${{ vars.HOST_KEY }}" >> ~/.ssh/known_hosts
      - name: Upload compose file and roll the container
        env:
          HOST: ${{ vars.SSH_HOST }}
        run: |
          scp compose/docker-compose.yml "deploy@${HOST}:/opt/nextxch/docker-compose.yml"
          scp "sites/${{ matrix.site }}.env.tag" "deploy@${HOST}:/opt/nextxch/tag.env"
          ssh "deploy@${HOST}" 'cd /opt/nextxch && docker compose --env-file .env --env-file tag.env pull && docker compose --env-file .env --env-file tag.env up -d'
      - name: Wait until the node is ready again
        env:
          HOST: ${{ vars.SSH_HOST }}
        run: |
          for i in $(seq 1 30); do
            ssh "deploy@${HOST}" 'curl -fsS http://127.0.0.1/health/ready' && exit 0
            sleep 10
          done
          echo "node did not become ready" >&2; exit 1
GitLab CI
# .gitlab-ci.yml: the same rolling update with GitLab CI
stages: [validate, deploy-a, deploy-b]

variables:
  NEXTXCH_TAG: "latest"     # pin a released version in production

validate:
  stage: validate
  image: docker:27
  script:
    - docker compose -f compose/docker-compose.yml config -q

.deploy: &deploy
  image: alpine:3.22
  before_script:
    - apk add --no-cache openssh-client curl
    - install -m 700 -d ~/.ssh && echo "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
    - echo "$HOST_KEY" >> ~/.ssh/known_hosts
  script:
    - scp compose/docker-compose.yml "deploy@$SSH_HOST:/opt/nextxch/"
    - ssh "deploy@$SSH_HOST" "cd /opt/nextxch && NEXTXCH_TAG=$NEXTXCH_TAG docker compose pull && NEXTXCH_TAG=$NEXTXCH_TAG docker compose up -d"
    - for i in $(seq 1 30); do ssh "deploy@$SSH_HOST" 'curl -fsS http://127.0.0.1/health/ready' && exit 0; sleep 10; done; exit 1
  resource_group: production   # serializes deployments
  rules: [ { if: '$CI_COMMIT_BRANCH == "main"' } ]

deploy-hetzner-a:
  <<: *deploy
  stage: deploy-a
  environment: { name: hetzner-a }

deploy-netcup-b:
  <<: *deploy
  stage: deploy-b
  environment: { name: netcup-b }
GitHub Actions:Kubernetes (L 方案)
# .github/workflows/deploy-k8s.yml: one Kubernetes cluster per provider, rolled one after another.
name: deploy-nextxch-k8s
on:
  push: { branches: [main], paths: ["k8s/**"] }
  workflow_dispatch:

concurrency: { group: deploy-k8s, cancel-in-progress: false }

jobs:
  helm:
    runs-on: ubuntu-latest
    strategy:
      max-parallel: 1
      matrix:
        cluster: [hetzner, netcup, strato]
    environment: k8s-${{ matrix.cluster }}
    steps:
      - uses: actions/checkout@v4
      - uses: azure/setup-helm@v4
      - name: Kubeconfig
        run: |
          mkdir -p ~/.kube
          echo "${{ secrets.KUBECONFIG_B64 }}" | base64 -d > ~/.kube/config
          chmod 600 ~/.kube/config
      - name: Helm upgrade (waits for readiness probes on /health/ready)
        run: |
          helm upgrade --install nextxch ./deploy/helm/nextxch \
            --namespace nextxch --create-namespace \
            -f k8s/values-common.yaml -f k8s/values-${{ matrix.cluster }}.yaml \
            --set image.tag=${{ vars.NEXTXCH_TAG }} \
            --wait --timeout 10m --atomic
故障轉移作業不應放在 CI 中
排程的 CI 執行既不精確到秒,也不保證執行。因此 DNS 容災轉移在各站台本身執行:作為 nextxch 內置代理程式,或作為執行指令碼的 systemd 服務(第 04 章),流水線僅負責部署。
郵件設定同樣來自 Git
網域、信箱、列表、規則、SMTP 及其他設定同樣以 YAML 形式保存在程式碼儲存庫中:nextxch-cli config plan 將計畫作為留言發布到提取要求,config apply --prune --yes 在合併後套用它。附現成 GitHub Actions 與 GitLab CI 檔案的指南:設定即程式碼 (GitOps)。

08 · 故障情境:具體會發生什麼事

Hetzner(站台 A,目前主節點)完全離線

sequenceDiagram
  participant S as Remote mail server
  participant A as Site A (Hetzner)
  participant B as Site B (netcup)
  participant C as Witness C
  participant D as DNS
  Note over A: Provider outage
  S->>A: SMTP to mx1
  A--xS: no connection
  S->>B: SMTP to mx2 (or retry)
  B--xS: without a primary the session fails, sender retries later
  Note over B,C: etcd majority B + C, leader key of A expires (ttl 30 s)
  B->>B: Patroni promotes PostgreSQL B to primary
  B->>B: nextxch reconnects (Target Session Attributes=primary)
  S->>B: retry
  B-->>S: 250 OK (commit synchronous or asynchronous)
  C->>D: failover job removes IP A from mail.example.com
  Note over D: clients follow after the TTL expires
站台 A 故障時的處理順序
時間會發生什麼事使用者會注意到什麼
0 sA 已失效。發往 mx1 的入站郵件失敗,寄件方改用 mx2(優先權相同)或稍後重試。[1]A 上的客戶端會遺失連線。
最長約 30 秒A 在 etcd 中的 leader 鍵在 ttl = 30 秒後過期;B 和 C 擁有多數票。[53]節點 B 在 /health/ready 上傳回 503,寫入操作等待。
約 30 至 60 秒Patroni 提升 B 為主節點(loop_wait 10 秒)。B 上的 nextxch 透過多主機連線字串找到新的主節點(重新檢查間隔 5 至 10 秒)。[63]B 重新接收郵件。
約 60 至 90 秒DNS 容錯移轉(代理:3 次失敗回合 × 30 秒,指令碼:3 × 20 秒)會將 IP A 從 mail.example.com 中移除。TTL(60 秒)到期後,新連線轉到 B。
1 至 5 分鐘設有自身最小 TTL 的解析器和帶 DNS 快取的客戶端會隨後跟進。Garage 繼續使用區域 B 和 C 執行(法定人數 3 取 2)。[61]客戶端會重新連線;網頁郵件工作階段保持有效(已簽署的無狀態工作階段)。

RPO

啟用 synchronous_mode 後,PostgreSQL 只有在第二個端點也收到認可後才確認該異動;以 250 OK 確認的訊息此時已存在於兩個端點。代價是:每次認可至少要等待端點之間的一次來回傳輸。不啟用 synchronous_mode 時,故障前最後幾秒的資料可能會遺失。設定 synchronous_mode_strict: false 時,若無剩餘複本,Patroni 會回退至非同步模式,以便繼續接收郵件。[56][54]

RTO

資料庫約 30 到 60 秒(Patroni 預設值),DNS 切換約 1 分鐘加 TTL,入站郵件透過第二個 MX 或發件方重試,無需等待。這些時間由預設值推算而來,並非實測:請在您自己的測試中驗證(硬停一個站台)。

netcup(站台 B,複本)離線

A 上的主節點繼續執行。沒有同步夥伴時,Patroni 切換為非同步模式(strict = false),故障轉移作業移除 IP B,入站郵件經由 mx1 流入。Garage 以 A 和 C 繼續執行。

僅 A 與 B 之間的連線中斷

仍能連通見證節點 C 的一方保有 etcd 多數票,保持或成為主節點。另一方失去多數票,Patroni 會將該側的主節點降級(failsafe_mode 僅在仍能連通所有成員時生效),DNS 故障轉移在該側也不會動作:內建代理連不到主節點,拿不到 leader 鎖;指令碼拿不到 etcd 鎖。不會發生腦裂。[55]

容錯回復

sequenceDiagram
  participant A as Site A
  participant B as Site B (primary)
  participant G as Garage
  participant D as DNS job
  A->>A: server back online, WireGuard up
  A->>B: Patroni: pg_rewind, then replica of B
  G->>A: missing objects are re-replicated
  A->>A: /health/ready = ready
  D->>D: successful checks
  D->>A: IP A back in mail.example.com
  Note over A,B: optional, planned: patronictl switchover back to A
站台 A 恢復

當 A 恢復運作時,B 保持為主節點。Patroni 透過 pg_rewind (use_pg_rewind: true) 將 A 重新納入為複本,Garage 重新同步遺漏的物件,容錯移轉作業只要一偵測到該處的 /health/ready 回報「ready」便會重新加入 IP A。不需要將主節點切回;若有需要,請在離峰時段透過 patronictl switchover 有計畫地執行。

09 · 備份、還原與 GoBD

複寫可防範中斷,而非防範失誤:不小心刪除的信箱在所有網站上會同時消失。因此請遵循 3-2-1 規則新增備份:三份複本、兩種媒體類型、一份異地備份。[59]

flowchart LR
  PG[("PostgreSQL primary or replica")] -->|"pgBackRest, continuous WAL"| R1["Repo 1: Hetzner Storage Box (SFTP)"]
  PG -->|"pgBackRest"| R2["Repo 2: S3 at another provider"]
  GA["Garage (3 zones)"] -->|"rclone copy hourly"| AR["Object Storage with Object Lock (GoBD)"]
  GA -->|"rclone copy"| R1
  R1 --> T["Quarterly restore test"]
  R2 --> T
備份流程
  • PostgreSQL:pgBackRest 配合連續 WAL 歸檔(時間點復原)。儲存庫 1 透過 SFTP 位於 Hetzner Storage Box(pgBackRest 自 2.46 起支援 SFTP;Storage Box 提供 SFTP、SCP、rsync、BorgBackup、Restic、Rclone、SMB、WebDAV),儲存庫 2 位於另一家服務商的 S3。兩者均加密。[58][15]
  • Blob:.eml 物件以 SHA-256 命名且永不修改。使用 rclone copy(而非 sync,因此絕不刪除)作為每小時複本已足夠。
  • GoBD 歸檔:Hetzner Object Storage 支援 GOVERNANCE 和 COMPLIANCE 模式的 Object Lock 以及版本控制;Object Lock 必須在建立儲存桶時啟用。建立儲存桶時設定預設保留期 (compliance),之後每個複製進來的物件都會自動鎖定。也可以讓 nextxch 直接寫入該儲存桶(S3 或 Hybrid 後端),但這樣資料塊的可用性取決於 Hetzner。在這種情況下,一旦配置了 WORM 模式(或 Storage:S3:ObjectLockEnabled),nextxch 會在啟動時建立缺失的、啟用 Object Lock 的儲存桶;GoBD 歸檔中的「檢查 S3 儲存桶」會顯示可達性、版本控制、Object Lock 模式和預設保留期。[18][17]
  • 測試還原:至少每季將 pgBackRest 還原到測試虛擬機器中,並從 blob 複本中抽樣開啟。
pgBackRest:/etc/pgbackrest/pgbackrest.conf
# /etc/pgbackrest/pgbackrest.conf on every PostgreSQL site.
# Repo 1: Hetzner Storage Box over SFTP (pgBackRest 2.46+), repo 2: S3 at another provider.
[global]
repo1-type=sftp
repo1-path=/pgbackrest
repo1-sftp-host=uXXXXXX.your-storagebox.de
repo1-sftp-host-port=23
repo1-sftp-host-user=uXXXXXX
repo1-sftp-private-key-file=/var/lib/postgresql/.ssh/id_ed25519
repo1-sftp-host-key-hash-type=sha256
repo1-retention-full=2
repo1-cipher-type=aes-256-cbc
repo1-cipher-pass=<long random secret, stored outside the repo>

repo2-type=s3
repo2-path=/pgbackrest
repo2-s3-endpoint=<s3 endpoint of the second provider>
repo2-s3-bucket=nextxch-pg-backup
repo2-s3-region=<region>
repo2-s3-uri-style=path
repo2-retention-full=4
repo2-cipher-type=aes-256-cbc
repo2-cipher-pass=<second secret>

archive-async=y
process-max=2
start-fast=y

[nextxch]
pg1-path=/var/lib/postgresql/18/main
pg1-port=5432

# Weekly full, daily differential (cron on every node; pgBackRest runs only where it can,
# use --repo and the "backup-standby" option to take backups from a replica).
#   0 2 * * 0  pgbackrest --stanza=nextxch --type=full backup
#   0 2 * * 1-6 pgbackrest --stanza=nextxch --type=diff backup
rclone:Blob 複製與 GoBD 儲存桶
# Blob copy (all .eml objects) from Garage to an independent target, every hour.
# ~/.config/rclone/rclone.conf (keys are placeholders)
[garage]
type = s3
provider = Other
endpoint = http://127.0.0.1:3900
region = garage
access_key_id = <garage key>
secret_access_key = <garage secret>

[archive]
type = s3
provider = Other
endpoint = <object storage endpoint>
access_key_id = <key>
secret_access_key = <secret>

# Content-addressed (SHA-256 names, never modified): "copy" is enough and never deletes.
#   rclone copy garage:nextxch archive:nextxch-archive --immutable --transfers 8 --checksum
# For a GoBD copy create the target bucket WITH Object Lock and a default retention
# (COMPLIANCE, e.g. 10 years) so every copied object is locked automatically.

10 · 擴展:使用者、儲存空間、Pod

flowchart LR
  S1["Start: 2 sites + witness"] --> S2["More mailboxes: add nextxch nodes per site"]
  S2 --> S3["DB grows: scale PostgreSQL VMs vertically (RAM, NVMe)"]
  S3 --> S4["More storage: add Garage nodes per zone"]
  S4 --> S5["Many mailboxes: Kubernetes per provider, HPA"]
擴展路徑
元件擴展方式注意
nextxch 節點 / Pod水平無狀態;每個站台增加節點或增加 Pod (HPA)。無需工作階段黏滯。
PostgreSQL 主節點垂直方向所有寫入都送往同一個主節點。應增加記憶體與更快的磁碟 (IOPS) 而非增加節點;shared_buffers 初始值為記憶體的 25%。nextxch 不使用唯讀複本。[57]
Blob 儲存區水平每個區域配置具備容量的更多 Garage 節點 (garage layout assign -c),資料將會重新平衡。SHA-256 去重與 Zstd 壓縮可降低需求。
SMTP透過 DNS具有相同優先順序的更多 MX 記錄可分攤負載;外寄佇列透過 SKIP LOCKED 分散到所有節點。
IMAP透過 DNS / LB長連線的 IDLE 工作階段保留在其所在節點上;來自其他節點的新郵件透過 LISTEN/NOTIFY 到達。新增節點後,只有在用戶端重新連線時負載才會分散。[7]
HTTPS(Webmail、ActiveSync、JMAP)透過 DNS / LB無狀態 HMAC 工作階段;任何請求都可以到達任意節點。

11 · 成本:哪裡可以節省,哪裡不能

儲存

  • nextxch 與見證節點使用共用 vCPU 方案;只有在資料庫 CPU 負載確有需要時才使用專屬核心。
  • 在 netcup 訂閱 12 個月(比價格頁面上的月費價格低 13%)。[22]
  • 使用內建代理(或您自己的指令碼)進行 DNS 容錯移轉,而非付費負載平衡器。
  • Blob 的 Zstd 壓縮(Storage:Compression)與 SHA-256 刪除重複。

不要節省的地方

  • PostgreSQL 節點的記憶體:任何未快取的內容在每次檢視資料夾時都會產生磁碟 I/O。
  • PostgreSQL 的磁碟 IOPS (NVMe);WAL 寫入決定每次投遞的延遲。
  • 第三個站台:沒有它就無法實現安全的自動故障轉移。
  • 在獨立目標位置進行經過測試的備份。

已錄入的價格(每月淨價,截至 2026 年 11 月 2 日)。netcup 和 STRATO 公布的是含 19% 加值稅的總價,此處已除以 1.19。Hetzner 另加主 IPv4 費用 €0.50。在核查當日,Hetzner 將所有雲端方案顯示為「currently unavailable」;無法確定這是庫存問題還是顯示問題. Hetzner 磁碟區的價格無法從官方網頁讀取,因此計算器中未包含。價格會變動:訂購前請向服務商核實。[12][10][22][23][30][15][16]

服務商方案vCPU記憶體磁碟€ 淨價 / 月
Hetzner CloudCX2324 GB40 GB€6.49
Hetzner CloudCX3348 GB80 GB€9.49
Hetzner CloudCX43816 GB160 GB€16.99
Hetzner CloudCX531632 GB320 GB€30.49
netcup VPSVPS 500 G12.524 GB64 GB€6.94
netcup VPSVPS 1000 G12.548 GB128 GB€12.18
netcup VPSVPS 2000 G12.5816 GB256 GB€22.62
netcup VPSVPS 4000 G12.51232 GB512 GB€38.12
netcup VPSVPS 8000 G12.51664 GB1024 GB€56.39
netcup Root ServerRS 1000 G12.548 GB128 GB€18.26
netcup Root ServerRS 2000 G12.5816 GB256 GB€34.20
netcup Root ServerRS 4000 G12.51232 GB512 GB€65.40
netcup Root ServerRS 8000 G12.51664 GB1024 GB€124.72
netcup Root ServerRS 12000 G12.52096 GB1536 GB€182.26
netcup Root ServerRS 16000 G12.524128 GB2048 GB€243.24
STRATO VPSVPS S12 GB60 GB€3.36
STRATO VPSVPS M24 GB120 GB€8.40
STRATO VPSVPS L48 GB240 GB€16.81
STRATO VPSVPS XL816 GB480 GB€32.77
STRATO VPSVPS XXL1224 GB720 GB€47.06
Hetzner Storage BoxBX11--1 TB€3.20
Hetzner Storage BoxBX21--5 TB€10.90
Hetzner Storage BoxBX31--10 TB€20.80
Hetzner Storage BoxBX41--20 TB€40.60
Hetzner Object Storage基礎價格,含 1 TB 儲存空間 + 1 TB 出站流量--1 TB€6.49

12 · 計算機:資源與成本

完全在瀏覽器中執行,無需外部服務。所用假設公開列在結果下方。

假設(未測量,請用您自己的資料核對)
  • 郵件資料量 = 信箱數 × 平均大小 × (1 + 成長率)^年數。不扣除重複資料刪除或壓縮的節省量(保守估算)。
  • PostgreSQL 容量 = 郵件量的 3%(後設資料、旗標、全文檢索索引),至少 2 GB。實際值透過 SELECT pg_database_size('nextxch') 取得。
  • PostgreSQL 記憶體 = 資料庫大小的 25%,至少 2 GB,向上取整至 2/4/8/16/32/64/96/128 GB。PostgreSQL 磁碟 = 2 × 資料庫大小(資料、WAL、保留空間)。
  • nextxch 程序:1 GB + 每啟動 1,000 個信箱加 1 GB(儲存庫中的 Kubernetes 限制為每個 Pod 1 GiB)。etcd + Garage + 作業系統:1 GB。見證節點:2 GB RAM。作業系統:20 GB 磁碟。
  • Garage replication_factor 3:每個區域 (站點或見證節點) 都儲存完整的郵件資料量。
  • 方案 L:每個服務商至少 2 個 Pod,每 1,500 個信箱 1 個 Pod,工作執行緒 8 GB;資料虛擬機器承載 PostgreSQL、etcd 與 Garage 區域。
  • 備份需求 = 3 × 資料庫大小(2 份完整備份 + WAL)+ 郵件量;目標:選擇能容納的最小 Hetzner Storage Box。
  • 授權價格取自本網站目前的價格目錄(級距價格適用於所有信箱,年費 / 12)。Cloudflare 以美元顯示,未計入歐元總額。

13 · 新增其他服務商(以 STRATO 為例)

  1. 訂購前:能否設定 PTR?STRATO:VPS 的反向 DNS 在客戶登入後的網域下方設定,必須先建立 A/AAAA 記錄,最多需要 24 小時。連接埠 25:針對獨立伺服器,STRATO 文件說明出站遭到封鎖,可透過客服解除封鎖;針對 VPS 則無相關規定文件。STRATO 不提供備援 IP。[31][32][30]
  2. 將新主機加入 Ansible 清單並指派專屬 WireGuard IP 與 Garage 區域,於所有站台新增對等節點,然後執行 Playbook。
  3. etcd:用 etcdctl member add 新增成員,並以 ETCD_INITIAL_CLUSTER_STATE=existing 啟動。有四個資料庫站台時,請保持 etcd 成員數為奇數。[48]
  4. Patroni 以複本身分啟動並自動複製。Garage:使用新區域執行 garage layout assign,然後執行 garage layout apply。
  5. DNS:將 IP 新增至 SPF,新增一筆優先權相同的 MX,將節點加入 DNS 容錯移轉清單(代理或指令碼),為新 MX 名稱新增 TLSA 記錄,設定新節點的 EHLO 名稱與 PTR,並將憑證擴充至該名稱。MTA-STS 策略會自動納入新 MX(自動 MX 清單);隨後發佈來自 DNS 顧問的新 _mta-sts TXT 值。
  6. 將該站台納入管線矩陣(Pipeline Matrix),並對新站台的故障情況進行一次測試。

14 · 限制與不足(誠實說明)

在編寫本指南時於程式碼中發現。其中四個缺口目前已修復:具備多個 MX 名稱的 MTA-STS、每個節點的 EHLO 名稱、自動建立的 Object Lock 儲存桶以及內建的 DNS 容錯移轉代理程式。其餘問題本指南按所述方式規避。

差距影響因應措施
DNS 容錯移轉代理(已關閉)內建,選用啟用:來自每個節點的健康狀態檢查,僅叢集主節點透過 Hetzner DNS 或 Cloudflare 變更 A/AAAA。其他 DNS 提供者(例如 deSEC):etcd 鎖定下的指令碼(第 04 章)。
多個 MX 的 MTA-STS(已解決)按網域政策列出所有 MX 名稱(DNS MX、伺服器與節點名稱,或帶萬用字元的自訂清單);政策 id 隨清單變更。每次變更 MX 後,請發布來自 DNS 顧問的 _mta-sts TXT 值。
每個節點的 EHLO 名稱(已解決)Smtp:HeloHostname 或在 /admin/ 中按節點設定,並按節點檢查 PTR;伺服器主機名稱在整個叢集內保持一致。-
只有一個 S3 目標不會雙寫至不同提供者的兩個 S3 儲存體;Object Lock 功能需要支援 Object Lock 的 S3。Garage 跨三個站點部署,另用 rclone 複製到 Object Lock 儲存貯體。
Object Lock 儲存貯體(已鎖定)設定 WORM 模式後,伺服器會在啟動時建立缺少 Object Lock 的儲存體局。已有但未啟用 Object Lock 的儲存體局會以警告和告警形式回報,因為 Object Lock 只能在建立時啟用。[18]可隨時在 GoBD 封存中透過「Check S3 bucket」進行檢查。
無內建備份伺服器中沒有針對資料庫和 Blob 的備份服務。pgBackRest 與 rclone(第 09 章)。
無讀取複本所有查詢均發送至主節點;唯讀複本在開發計畫中僅列為「按需提供」。對 PostgreSQL 主節點進行垂直擴展。
無實測的規模基準計算器中的記憶體與資料庫大小為假設值。以您自己的測量結果覆寫。

常見問題集

nextxch 可以在多個服務商之間以雙主動(active-active)方式執行嗎?

可以。啟用 Cluster:Enabled=true 並使用 PostgreSQL 後,任意數量的主機透過 LISTEN/NOTIFY、UNLOGGED 表格和諮詢鎖共用狀態。所有節點都必須能存取同一個 PostgreSQL 主節點和同一個 S3 Blob 儲存;跨服務商時透過 WireGuard 網路實現。

我需要負載平衡器或 Anycast 嗎?

不需要。入站郵件僅需多個具有相同優先權的 MX 記錄(RFC 5321 第 5.1 節)。IMAP、提交與 HTTPS 需要一個具有短 TTL 的名稱,其 A 記錄由健康狀態檢查作業維護。Anycast/BGP 切實可行但較為複雜。

我至少需要多少個站點?

三票:兩個完整站點加一個小型見證節點(etcd、Garage 區域、容錯移轉檢查程式),或三個完整站點。只有兩個站點時,任何一方都無法可靠判斷對方是故障了還是僅僅連線中斷(腦裂)。

當服務提供者離線時,郵件會遺失嗎?

寄件者會持續重試至少 4 至 5 天(RFC 5321 第 4.5.4.1 節)。藉由 Patroni synchronous_mode 與 Garage replication_factor 3,經 250 OK 確認的訊息已儲存於第二個站台上。

15 · 參考來源

所有外部事實均已於 2026 年 11 月 2 日對照以下官方來源進行查核。無法核實的內容已在內文中註明。

  1. RFC 5321 (SMTP): 4.1.4 EHLO, 4.5.4.1 retry, 5.1 MX: https://www.rfc-editor.org/rfc/rfc5321.html
  2. RFC 7208 (SPF): 4.6.4 DNS lookup limit, 5.6 ip4/ip6: https://www.rfc-editor.org/rfc/rfc7208.html
  3. RFC 6376 (DKIM): 3.1 selectors: https://www.rfc-editor.org/rfc/rfc6376.html
  4. RFC 8461 (MTA-STS): 3.2, 4.1 mx patterns: https://www.rfc-editor.org/rfc/rfc8461.html
  5. RFC 7672 (DANE for SMTP): 3.1 TLSA 3 1 1: https://www.rfc-editor.org/rfc/rfc7672.html
  6. RFC 8314 (implicit TLS 465/993/995): https://www.rfc-editor.org/rfc/rfc8314.html
  7. RFC 2177 (IMAP IDLE, re-issue every 29 minutes): https://www.rfc-editor.org/rfc/rfc2177.html
  8. Google:電子郵件發件人指南(正向與反向 DNS):https://support.google.com/a/answer/81126
  9. Hetzner 文件:Floating IPs:https://docs.hetzner.com/cloud/floating-ips/overview
  10. Hetzner 文件:IPv4 定價:https://docs.hetzner.com/general/others/ipv4-pricing
  11. Hetzner 文件:Robot 容錯移轉 IP:https://docs.hetzner.com/robot/dedicated-server/ip/failover
  12. Hetzner Cloud:具成本效益的方案:https://www.hetzner.com/cloud/cost-optimized/
  13. Hetzner 文件:Cloud server 常見問題(連接埠 25/465):https://docs.hetzner.com/cloud/servers/faq/
  14. Hetzner 文件:PTR 記錄:https://docs.hetzner.com/networking/dns/record-types/ptr-record/
  15. Hetzner Storage Box(價格、協定):https://www.hetzner.com/storage/storage-box/
  16. Hetzner Object Storage(價格):https://www.hetzner.com/storage/object-storage/
  17. Hetzner 文件:Object Storage 概觀:https://docs.hetzner.com/storage/object-storage/overview
  18. Hetzner 文件:Object Lock 與保留:https://docs.hetzner.com/storage/object-storage/howto-protect-objects/protect-object-lock-retention/
  19. Hetzner 文件:Load Balancer 常見問題:https://docs.hetzner.com/cloud/load-balancers/faq
  20. Hetzner 文件:Networks 常見問題:https://docs.hetzner.com/cloud/networks/faq
  21. Hetzner 文件:DNS(主控台與 API):https://docs.hetzner.com/networking/dns/overview/
  22. netcup: VPS G12.5 prices: https://www.netcup.com/de/server/vps
  23. netcup: Root Server G12.5 prices: https://www.netcup.com/de/server/root-server
  24. netcup Helpcenter: IP addresses and failover: https://www.netcup.com/en/helpcenter/documentation/server/ip
  25. netcup: server extensions (failover IP prices): https://www.netcup.com/de/server/kvm-server-erweiterungen
  26. netcup Helpcenter: firewall (policy "netcup Mail block"): https://www.netcup.com/en/helpcenter/documentation/server/firewall
  27. netcup Helpcenter: network / rDNS: https://www.netcup.com/en/helpcenter/documentation/server/network-server
  28. netcup: Storage Space (NFS): https://www.netcup.com/en/server/storage-space
  29. netcup Helpcenter: DNS API: https://www.netcup.com/en/helpcenter/documentation/domain/our-api
  30. STRATO:VPS Linux 價格:https://www.strato.de/server/linux-vserver/
  31. STRATO 常見問題:VPS 的反向 DNS:https://www.strato.de/faq/server/wie-kann-ich-reverse-dns-fuer-meinen-vps-vds-einrichten/
  32. STRATO 常見問題:獨立伺服器網路防火牆(連接埠 25):https://www.strato.de/faq/server/wie-stelle-ich-die-netzwerk-firewall-bei-meinem-windows-root-server-ein/
  33. Cloudflare:負載平衡附加元件價格:https://www.cloudflare.com/plans/network-cdn/
  34. Cloudflare 說明文件:負載平衡限制(健康檢查間隔):https://developers.cloudflare.com/load-balancing/reference/limitations/
  35. Cloudflare 說明文件:負載平衡 DNS 記錄(MX/SRV 僅限 Enterprise):https://developers.cloudflare.com/load-balancing/load-balancers/dns-records/
  36. Cloudflare 說明文件:代理模式(僅 DNS):https://developers.cloudflare.com/load-balancing/understand-basics/proxy-modes/
  37. Cloudflare 說明文件:各方案支援的 Spectrum 通訊協定:https://developers.cloudflare.com/spectrum/protocols-per-plan/
  38. Cloudflare 文件:DNS TTL:https://developers.cloudflare.com/dns/manage-dns-records/reference/ttl/
  39. Cloudflare API:編輯 DNS 記錄:https://developers.cloudflare.com/api/resources/dns/subresources/records/methods/edit/
  40. deSEC:網域與最小 TTL:https://desec.readthedocs.io/en/latest/dns/domains.html
  41. Akamai/Linode:IP 容災切換(BGP、相同資料中心):https://techdocs.akamai.com/cloud-computing/docs/configure-failover-on-a-compute-instance
  42. Akamai:NodeBalancer 定價:https://www.akamai.com/cloud/pricing/nodebalancers
  43. Vultr:BGP 要求:https://docs.vultr.com/configuring-bgp-on-vultr
  44. RIPE NCC:申請 AS 號碼:https://www.ripe.net/manage-ips-and-asns/as-numbers/request-an-as-number/
  45. Proxmox VE: Cluster Manager (corosync latency, QDevice): https://pve.proxmox.com/wiki/Cluster_Manager
  46. Proxmox Backup Server:資料儲存(含 S3):https://pbs.proxmox.com/docs/storage.html
  47. WireGuard:https://www.wireguard.com/
  48. k3s:使用嵌入式 etcd 的高可用:https://docs.k3s.io/datastore/ha-embedded
  49. k3s:分散式混合或多雲叢集:https://docs.k3s.io/networking/distributed-multicloud
  50. etcd:調校(心跳、選舉逾時):https://etcd.io/docs/v3.5/tuning/
  51. Talos Linux: KubeSpan: https://docs.siderolabs.com/talos/v1.11/networking/kubespan
  52. CloudNativePG:複本叢集:https://cloudnative-pg.io/docs/current/replica_cluster
  53. Patroni:動態設定(ttl、loop_wait、retry_timeout):https://patroni.readthedocs.io/en/latest/dynamic_configuration.html
  54. Patroni:複製模式(synchronous_mode、strict):https://patroni.readthedocs.io/en/latest/replication_modes.html
  55. Patroni:DCS failsafe 模式:https://patroni.readthedocs.io/en/latest/dcs_failsafe_mode.html
  56. PostgreSQL 18:同步複寫:https://www.postgresql.org/docs/current/warm-standby.html#SYNCHRONOUS-REPLICATION
  57. PostgreSQL 18:shared_buffers:https://www.postgresql.org/docs/current/runtime-config-resource.html
  58. pgBackRest(S3 與 SFTP 儲存庫):https://pgbackrest.org/
  59. CISA:資料備份選項 (3-2-1):https://www.cisa.gov/sites/default/files/publications/data_backup_options.pdf
  60. Garage:專案首頁 (多資料中心,200 ms / 50 Mbps):https://garagehq.deuxfleurs.fr/
  61. Garage:設定 (replication_factor、仲裁):https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/
  62. Garage:S3 相容性 (無 Object Lock,無版本控制):https://garagehq.deuxfleurs.fr/documentation/reference-manual/s3-compatibility/
  63. Npgsql:容錯移轉與負載平衡(多主機):https://www.npgsql.org/doc/failover-and-load-balancing.html
  64. Mermaid 12.2.0 (MIT),在此網站提供:https://www.npmjs.com/package/mermaid