Skip to content

Deploying a Mailu cluster on Ubuntu 22.04 with a PostgreSQL backend

Two-host Mailu install on Ubuntu 22.04 with an external PostgreSQL backend, shared maildir over NFS, and HAProxy in front for SMTP/IMAP traffic — a multi-host upgrade over the default single-node compose.

You inherit a Mailu single-host install that’s been running fine for two years, but the company is rolling out a new tenant tier with an uptime commitment that doesn’t survive a kernel update. The off-the-shelf docker-compose Mailu is built for one box — Postfix, Dovecot, Rspamd, the admin webmail, and an internal SQLite or MySQL on the same loopback. To split it into something a team can actually operate — front-end mail nodes behind HAProxy, an external PostgreSQL for accounts and aliases, a shared maildir over NFS — you need to break Mailu apart along the seams it already has, not fight the upstream config.

What’s happening

Mailu is a compose stack with five real persistence dependencies: the SQL database (accounts, aliases, fetchmail jobs, audit log), Redis (rate limits, override quotas, anti-spam state), the mail volume (maildir + sieve scripts), the DKIM keys directory, and the Rspamd Redis (greylist, fuzzy hashes, statistics). The compose ships an admin container that’s the only thing that reads/writes the SQL. Postfix and Dovecot read from the admin’s HTTP API for account lookups and from the mail volume for storage. The implication: if you put SQL on an external PostgreSQL, Redis on an external cluster, and the mail volume on a shared filesystem mounted on each compose host, you can run two or more Mailu compose stacks in parallel behind a TCP load balancer, and they will all see the same accounts and the same mail.

Two host counts make sense. A two-host front layer in active/active with HAProxy round-robin gets you bounded downtime on a host loss — connections in-flight die, new connections continue. PostgreSQL behind it is whatever HA tier you already run (managed PaaS, Patroni, RDS Multi-AZ; the database is not the interesting failure surface here). The mail volume is the real trade-off: shared NFS works and is what the upstream Mailu docs document, but it serializes writes through one storage head, so size the NFS host accordingly. The alternatives — GlusterFS, JuiceFS, an S3-backed FUSE — exist but each has its own failure mode that surprises an operator in production, so unless you have a specific reason, NFS over a low-latency private network is the safe default.

What this gets you: zero-downtime rolling upgrades of front-end mail nodes (drain one out of HAProxy, upgrade Mailu compose, drain back in, repeat), a database tier you operate the same way you operate every other Postgres, and the ability to keep one front-end running while the other is rebuilt from scratch. What it doesn’t get you: load capacity. SMTP and IMAP are not CPU-bound at the front; the bottleneck is the maildir filesystem. Scaling beyond two front-ends without sharding mailboxes by tenant is mostly wasted compute.

How to verify

HAProxy backends from the LB host:

echo "show stat" | socat stdio /run/haproxy/admin.sock \
  | awk -F, '$1 ~ /^smtp|^imap|^submission/{print $1,$2,$18}'

You want both backend members UP. If one is DOWN, the front-end node is either failing the TCP health check (check port 25) or the compose stack hasn’t finished starting — docker compose ps on that host will tell you which.

Account lookups going through to PostgreSQL (not a stale internal cache):

# On a front-end Mailu host
docker compose exec admin python -c \
  "from mailu import models, app
   app.app_context().push()
   print(models.User.query.count())"

If the count matches what’s in the SQL database, the API is wired correctly:

SELECT count(*) FROM "user";

Shared maildir is actually shared (the critical end-to-end test):

# On node1 — create a sentinel file in a mailbox
docker compose exec dovecot \
  touch /mail/example.com/test_user/.HA_SENTINEL

# On node2
docker compose exec dovecot \
  ls -la /mail/example.com/test_user/.HA_SENTINEL

If node2 can’t see it, the NFS mount is wrong or only one node mounted it — fix that before delivering any production mail. A divergent maildir corrupts UIDs and breaks IMAP clients in ways that are very hard to recover from.

The fix

Save the installer as /root/setup-mailu-node.sh and run it on both front-end hosts after editing the variables. It assumes you’ve already provisioned (a) a PostgreSQL 16 instance reachable on a private network, (b) an NFS export on a third host with the mail directory mounted at /srv/mailu/mail, and (c) DNS for the mail.example.com hostname pointing at the HAProxy VIP, not the front-end hosts.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 Mailu cluster front-end installer
### Run on each Mailu front-end node after editing variables below
### Prereqs: external PostgreSQL, external Redis, NFS export for /mail

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

# === EDIT PER NODE ===
NODE_NAME="mailu01"
NODE_IP="10.10.0.51"
PUBLIC_HOSTNAME="mail.example.com"
POSTMASTER="admin"
DB_HOST="10.10.0.60"
DB_NAME="mailu"
DB_USER="mailu"
DB_PASSWORD="CHANGE_ME_DB"
REDIS_HOST="10.10.0.61"
REDIS_PORT=6379
NFS_SERVER="10.10.0.62"
NFS_EXPORT="/srv/mailu/mail"
SECRET_KEY="CHANGE_ME_64_HEX_CHARS"
INITIAL_ADMIN_PASSWORD="CHANGE_ME_BOOTSTRAP"
TIMEZONE="UTC"
# =====================

echo
echo "========================================"
echo "Mailu node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo

echo "==> Base packages"
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get -y install \
  curl wget gnupg ca-certificates lsb-release \
  vim jq tar gzip iproute2 net-tools chrony \
  fail2ban unattended-upgrades nfs-common \
  postgresql-client-16

systemctl enable --now chrony

echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd

echo "==> Timezone"
timedatectl set-timezone "${TIMEZONE}"

echo "==> Docker engine"
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
  https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" \
  > /etc/apt/sources.list.d/docker.list

apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io \
  docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker

echo "==> NFS mount for /mail"
mkdir -p /srv/mailu/mail
cat >> /etc/fstab <<EOF
${NFS_SERVER}:${NFS_EXPORT}  /srv/mailu/mail  nfs4  rw,hard,intr,timeo=600,retrans=2,_netdev  0  0
EOF
mount /srv/mailu/mail
mountpoint -q /srv/mailu/mail || { echo "NFS mount failed"; exit 1; }

echo "==> Sanity-check Postgres reachability"
PGPASSWORD="${DB_PASSWORD}" psql \
  -h "${DB_HOST}" -U "${DB_USER}" -d "${DB_NAME}" -c 'SELECT version();'

echo "==> Mailu compose checkout"
mkdir -p /opt/mailu
cd /opt/mailu
curl -fsSL https://setup.mailu.io/2.0/file/$(uuidgen)/docker-compose.yml \
  -o docker-compose.yml.template
# We replace the template's local DB/Redis with our externals
cat > docker-compose.yml <<EOF
version: "3.8"

services:
  front:
    image: ghcr.io/mailu/nginx:2.0
    restart: always
    env_file: mailu.env
    logging:
      driver: journald
    ports:
      - "25:25"
      - "465:465"
      - "587:587"
      - "143:143"
      - "993:993"
      - "110:110"
      - "995:995"
      - "127.0.0.1:8080:80"
    volumes:
      - "/opt/mailu/certs:/certs"
      - "/opt/mailu/overrides/nginx:/overrides:ro"

  admin:
    image: ghcr.io/mailu/admin:2.0
    restart: always
    env_file: mailu.env
    volumes:
      - "/opt/mailu/data:/data"
      - "/opt/mailu/dkim:/dkim"

  smtp:
    image: ghcr.io/mailu/postfix:2.0
    restart: always
    env_file: mailu.env
    volumes:
      - "/opt/mailu/mailqueue:/queue"
      - "/opt/mailu/overrides/postfix:/overrides:ro"

  imap:
    image: ghcr.io/mailu/dovecot:2.0
    restart: always
    env_file: mailu.env
    volumes:
      - "/srv/mailu/mail:/mail"
      - "/opt/mailu/overrides/dovecot:/overrides:ro"

  antispam:
    image: ghcr.io/mailu/rspamd:2.0
    hostname: antispam
    restart: always
    env_file: mailu.env
    volumes:
      - "/opt/mailu/filter:/var/lib/rspamd"
      - "/opt/mailu/overrides/rspamd:/etc/rspamd/override.d:ro"

  webmail:
    image: ghcr.io/mailu/webmail:2.0
    restart: always
    env_file: mailu.env
    volumes:
      - "/opt/mailu/webmail:/data"
EOF

echo "==> Mailu env"
cat > /opt/mailu/mailu.env <<EOF
SECRET_KEY=${SECRET_KEY}
DOMAIN=$(echo "${PUBLIC_HOSTNAME}" | sed 's/^mail\.//')
HOSTNAMES=${PUBLIC_HOSTNAME}
POSTMASTER=${POSTMASTER}
TLS_FLAVOR=letsencrypt
ADMIN=true
WEBMAIL=roundcube
ANTIVIRUS=
ANTISPAM=true
WEBDAV=
FETCHMAIL_ENABLED=true

# Externalized state
DB_FLAVOR=postgresql
DB_HOST=${DB_HOST}
DB_PORT=5432
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PW=${DB_PASSWORD}

REDIS_ADDRESS=${REDIS_HOST}:${REDIS_PORT}

INITIAL_ADMIN_ACCOUNT=admin
INITIAL_ADMIN_DOMAIN=$(echo "${PUBLIC_HOSTNAME}" | sed 's/^mail\.//')
INITIAL_ADMIN_PW=${INITIAL_ADMIN_PASSWORD}
INITIAL_ADMIN_MODE=ifmissing

MESSAGE_SIZE_LIMIT=50000000
RELAYNETS=
RELAYHOST=
REJECT_UNLISTED_RECIPIENT=true
DMARC_RUA=${POSTMASTER}
DMARC_RUF=${POSTMASTER}

LOG_DRIVER=journald
LOG_LEVEL=WARNING

TZ=${TIMEZONE}

# Front-end only — TLS cert lives on local disk; renew via a separate cronjob
WEB_ADMIN=/admin
WEB_WEBMAIL=/webmail
WEBROOT_REDIRECT=/webmail

# Cluster awareness
POD_ADDRESS_RANGE=
EOF

mkdir -p /opt/mailu/certs /opt/mailu/data /opt/mailu/dkim \
         /opt/mailu/mailqueue /opt/mailu/filter /opt/mailu/webmail \
         /opt/mailu/overrides/nginx /opt/mailu/overrides/postfix \
         /opt/mailu/overrides/dovecot /opt/mailu/overrides/rspamd

echo "==> Postfix override: do not run a local SQL — use admin API only"
cat > /opt/mailu/overrides/postfix/main.cf <<'POSTFIX'
# Aggregated transports come from admin API; everything else stays default
maximal_queue_lifetime = 3d
bounce_queue_lifetime = 3d
POSTFIX

echo "==> fail2ban (SMTP/IMAP)"
cat > /etc/fail2ban/jail.d/mailu.local <<'FAIL2BAN'
[postfix]
enabled = true
maxretry = 5
findtime = 10m
bantime = 1h

[dovecot]
enabled = true
maxretry = 5
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

echo "==> Bringing up Mailu"
cd /opt/mailu
docker compose pull
docker compose up -d

echo "==> Waiting for admin to come up and bootstrap DKIM"
for i in {1..30}; do
  if docker compose exec admin curl -fs http://localhost/internal/postfix/sender/login/test >/dev/null 2>&1; then
    break
  fi
  sleep 5
done

echo
echo "========================================"
echo "DONE on ${NODE_NAME}"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ":(25|110|143|465|587|993|995)\b" || true
echo
echo "Mailu containers:"
docker compose ps
echo
echo "DKIM key path (this is what to publish in DNS once for the whole cluster):"
echo "  /opt/mailu/dkim/<domain>.dkim.key"
echo
echo "NOTE: the DKIM directory is local. If you upgrade two nodes at once, generate"
echo "DKIM on node1, then rsync /opt/mailu/dkim from node1 to node2 BEFORE bringing"
echo "node2 up — otherwise mail signed by node2 will fail DKIM verification."

After both front-end nodes are up, configure HAProxy on a separate load balancer host. The relevant config — kept short because it’s the simple part — looks like:

frontend smtp_in
  bind :25
  default_backend smtp_backend

backend smtp_backend
  mode tcp
  option tcp-check
  tcp-check connect port 25
  tcp-check expect rstring ^220
  server mailu01 10.10.0.51:25 check inter 5s fall 3 rise 2
  server mailu02 10.10.0.52:25 check inter 5s fall 3 rise 2

frontend submission_in
  bind :587
  default_backend submission_backend

backend submission_backend
  mode tcp
  option tcp-check
  tcp-check connect port 587
  server mailu01 10.10.0.51:587 check inter 5s fall 3 rise 2
  server mailu02 10.10.0.52:587 check inter 5s fall 3 rise 2

frontend imap_in
  bind :993
  default_backend imap_backend

backend imap_backend
  mode tcp
  balance source                # sticky by client IP — keeps Dovecot caches warm
  server mailu01 10.10.0.51:993 check inter 5s fall 3 rise 2
  server mailu02 10.10.0.52:993 check inter 5s fall 3 rise 2

For IMAP specifically, use balance source (sticky by client IP) rather than round-robin: Dovecot’s per-mailbox dictionary cache is local to a node, and bouncing the same user between nodes invalidates caches and slows IMAP for that user. SMTP doesn’t have this concern — round-robin is fine.

For Mailu clusters where you don’t want to operate the database, the NFS head, the HAProxy, and the DKIM key replication yourself, our team runs the full stack under Managed Cloud Ops on top of managed cloud compute with quarterly drills — start a scoping call.