Skip to content

Deploying Stalwart Mail on AlmaLinux 9 (production-ready)

Stand up a hardened Stalwart Mail Server on AlmaLinux 9 — single Rust binary, SMTP + IMAP + JMAP, systemd unit, Let's Encrypt for STARTTLS and IMAPS, RocksDB store.

You bring up Stalwart because the team is tired of running three Mailcow containers and four config files to do what one Rust binary now does in 80 MB of memory. The installer pulls the binary, generates a self-signed cert, opens 25/465/587/993/4190, and you can send and receive within five minutes. The danger is exactly the same as with every other mail server: the protocol-level work is correct out of the box, the perimeter is not. There is no Let’s Encrypt cert on the public interfaces, the DKIM key Stalwart generated is sitting in the database with no DNS record, fail2ban doesn’t know about Stalwart’s structured logs, and the admin API is bound to the same socket as the public IMAP — which means anyone who finds the admin port has the keys to the mailbox.

What’s happening

A production-ready Stalwart needs: a Let’s Encrypt certificate wired in for STARTTLS on 25/587, implicit TLS on 465/993, ManageSieve on 4190, and the JMAP/admin UI on 443; the JMAP admin endpoint bound to localhost or behind nginx with allowlists, never directly to the public interface; RocksDB or SQLite as the store (RocksDB scales further but SQLite is simpler — both are file-backed, no separate database to run); rDNS aligned with the SMTP banner; per-domain DKIM keys generated through the admin UI and the corresponding TXT records published in DNS before the first outbound message; rate-limiting against SMTP AUTH brute-force, either via Stalwart’s built-in throttle rules or fail2ban tailing the structured log; and a systemd unit with LimitNOFILE=64000 because a single Stalwart process can hold thousands of open IMAP sessions and the default 1024 limit collapses under any real concurrency. Stalwart is a single binary, but it is still a mail server — the operational discipline is identical.

How to verify

After install, the listeners should look like this:

ss -lntp | grep -E ':(25|443|465|587|993|4190|8080)\b'
# 0.0.0.0:25     stalwart-mail
# 0.0.0.0:465   stalwart-mail
# 0.0.0.0:587   stalwart-mail
# 0.0.0.0:993   stalwart-mail
# 0.0.0.0:4190  stalwart-mail
# 0.0.0.0:443   nginx
# 127.0.0.1:8080 stalwart-mail (admin/JMAP)

The admin port (8080) must be on 127.0.0.1. STARTTLS on submission and the cert on IMAPS:

openssl s_client -starttls smtp -crlf -connect mail.example.com:587 -servername mail.example.com </dev/null 2>/dev/null | grep -E 'subject=|issuer='
openssl s_client -connect mail.example.com:993 -servername mail.example.com </dev/null 2>/dev/null | grep -E 'subject=|issuer='

DNS sanity:

dig +short MX example.com
dig +short A mail.example.com
dig +short -x <your-ip>
dig +short TXT default._domainkey.example.com

If the DKIM TXT does not resolve, Stalwart is signing outbound mail with a key that does not exist in DNS — every message will fail DKIM at the receiver.

The fix

Save the script below as /root/setup-stalwart-almalinux9.sh, then run it. It performs the full installer flow on a fresh AlmaLinux 9.x VM: base update + EPEL, kernel/network tuning, file limits, removes postfix and sendmail from the host so nothing competes for port 25, hardens SSH while keeping root key access, configures firewalld with the right rules, enables dnf-automatic.timer for security updates, downloads the latest Stalwart Mail Server binary, creates a stalwart service user, runs the non-interactive --init to generate a baseline TOML config under /opt/stalwart, switches the store to RocksDB, binds the management API to 127.0.0.1:8080, writes a systemd unit with LimitNOFILE=64000, installs nginx as a TLS-terminating reverse proxy for JMAP/admin with a Let’s Encrypt cert, configures Stalwart to use the same Let’s Encrypt cert for SMTP/IMAPS via the file watcher, configures fail2ban for SSH plus a Stalwart SMTP AUTH jail, and prints the bootstrap admin credentials and DKIM seed at the end.

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

### AlmaLinux 9.x Stalwart Mail Server clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs Stalwart Mail with RocksDB store
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${MAIL_HOSTNAME:?Set MAIL_HOSTNAME, e.g. mail.example.com}"
: "${PRIMARY_DOMAIN:?Set PRIMARY_DOMAIN, e.g. example.com}"
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL}"
: "${TIMEZONE:=America/Toronto}"

echo
echo "========================================"
echo "Stalwart AlmaLinux 9.x Setup"
echo "Hostname:       ${MAIL_HOSTNAME}"
echo "Primary domain: ${PRIMARY_DOMAIN}"
echo "========================================"
echo

echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y update

echo "==> Installing base packages"
dnf -y install \
  vim curl wget ca-certificates gnupg2 \
  chrony fail2ban dnf-automatic \
  policycoreutils-python-utils \
  lsof tcpdump bind-utils \
  tar gzip unzip iproute net-tools jq

echo "==> Enabling time sync"
systemctl enable --now chronyd
timedatectl set-ntp true
timedatectl set-timezone "${TIMEZONE}"

echo "==> Removing host MTAs that would collide with port 25"
dnf -y remove postfix sendmail || true

echo "==> Configuring SELinux to enforcing on next boot"
if [[ -f /etc/selinux/config ]]; then
  sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
fi
setenforce 1 2>/dev/null || true

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-stalwart.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
SYSCTL

modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

cat > /etc/security/limits.d/99-stalwart.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4
sshd -t
systemctl restart sshd

echo "==> Configuring firewalld"
dnf -y install firewalld
systemctl enable --now firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=smtp
firewall-cmd --permanent --add-service=smtps
firewall-cmd --permanent --add-service=smtp-submission
firewall-cmd --permanent --add-service=imaps
firewall-cmd --permanent --add-port=4190/tcp
firewall-cmd --reload

echo "==> Configuring automatic security updates"
cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes

[emitters]
emit_via = stdio

[base]
debuglevel = 1
DNFAUTO
systemctl enable --now dnf-automatic.timer

echo "==> Creating stalwart-mail service user"
id -u stalwart-mail >/dev/null 2>&1 || useradd --system --home /opt/stalwart --shell /usr/sbin/nologin stalwart-mail
install -d -o stalwart-mail -g stalwart-mail /opt/stalwart /opt/stalwart/etc /opt/stalwart/data /opt/stalwart/queue /opt/stalwart/reports /opt/stalwart/logs

echo "==> Downloading Stalwart Mail Server"
STALWART_TAG="$(curl -s https://api.github.com/repos/stalwartlabs/mail-server/releases/latest | jq -r .tag_name)"
cd /tmp
curl -fsSL "https://github.com/stalwartlabs/mail-server/releases/download/${STALWART_TAG}/stalwart-mail-x86_64-unknown-linux-gnu.tar.gz" \
  -o stalwart-mail.tar.gz
tar -xzf stalwart-mail.tar.gz
install -m 0755 -o root -g root stalwart-mail /usr/local/bin/stalwart-mail

echo "==> Initialising Stalwart config (RocksDB store)"
ADMIN_PASSWORD="$(openssl rand -hex 16 | tee /root/.stalwart_admin_password)"
sudo -u stalwart-mail /usr/local/bin/stalwart-mail \
  --init "/opt/stalwart" \
  --no-input || true

# Write a deterministic configuration over whatever --init produced
cat > /opt/stalwart/etc/config.toml <<TOML
[server]
hostname = "${MAIL_HOSTNAME}"

[server.listener."smtp"]
bind = ["[::]:25"]
protocol = "smtp"

[server.listener."submission"]
bind = ["[::]:587"]
protocol = "smtp"
tls.implicit = false

[server.listener."submissions"]
bind = ["[::]:465"]
protocol = "smtp"
tls.implicit = true

[server.listener."imaps"]
bind = ["[::]:993"]
protocol = "imap"
tls.implicit = true

[server.listener."sieve"]
bind = ["[::]:4190"]
protocol = "managesieve"

[server.listener."http"]
bind = ["127.0.0.1:8080"]
protocol = "http"

[storage]
data = "rocksdb"
fts = "rocksdb"
blob = "rocksdb"
lookup = "rocksdb"
directory = "internal"

[store."rocksdb"]
type = "rocksdb"
path = "/opt/stalwart/data"
compression = "lz4"

[directory."internal"]
type = "internal"
store = "rocksdb"

[certificate."default"]
cert = "%{file:/etc/letsencrypt/live/${MAIL_HOSTNAME}/fullchain.pem}%"
private-key = "%{file:/etc/letsencrypt/live/${MAIL_HOSTNAME}/privkey.pem}%"

[server.tls]
certificate = "default"
sni = [
  { subject = "${MAIL_HOSTNAME}", certificate = "default" }
]

[session.rcpt]
relay = false
max-recipients = 25

[session.throttle."concurrent-smtp"]
key = "remote-ip"
concurrency = 10
enable = true

[session.throttle."auth-rate"]
key = "remote-ip"
rate = "30/1m"
enable = true

[queue.outbound]
hostname = "${MAIL_HOSTNAME}"
next-hop = "local"

[authentication.fallback-admin]
user = "admin"
secret = "${ADMIN_PASSWORD}"

[tracer."stdout"]
type = "stdout"
level = "info"
ansi = false
enable = true
TOML

chown -R stalwart-mail:stalwart-mail /opt/stalwart

echo "==> Writing systemd unit"
cat > /etc/systemd/system/stalwart-mail.service <<'UNIT'
[Unit]
Description=Stalwart Mail Server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=stalwart-mail
Group=stalwart-mail
WorkingDirectory=/opt/stalwart
ExecStart=/usr/local/bin/stalwart-mail --config /opt/stalwart/etc/config.toml
Restart=on-failure
RestartSec=5s
LimitNOFILE=64000
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
ProtectSystem=full
ProtectHome=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
UNIT

echo "==> Installing nginx + Let's Encrypt"
dnf -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/conf.d/stalwart.conf <<NGINX
server {
    listen 80;
    server_name ${MAIL_HOSTNAME};
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://\$host\$request_uri; }
}

server {
    listen 443 ssl http2;
    server_name ${MAIL_HOSTNAME};

    ssl_certificate /etc/letsencrypt/live/${MAIL_HOSTNAME}/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/${MAIL_HOSTNAME}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    client_max_body_size 100m;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_read_timeout 300s;
    }
}
NGINX

mkdir -p /var/www/html

# Issue cert before starting Stalwart so the file references resolve
systemctl enable --now nginx
certbot --nginx -n --agree-tos -m "${LETSENCRYPT_EMAIL}" -d "${MAIL_HOSTNAME}"
systemctl reload nginx

# Make sure stalwart-mail can read the live cert
chmod 0755 /etc/letsencrypt/live /etc/letsencrypt/archive 2>/dev/null || true

# Reload hook so renewal triggers a Stalwart restart
mkdir -p /etc/letsencrypt/renewal-hooks/deploy
cat > /etc/letsencrypt/renewal-hooks/deploy/stalwart.sh <<'HOOK'
#!/usr/bin/env bash
systemctl reload nginx || true
systemctl reload stalwart-mail || systemctl restart stalwart-mail || true
HOOK
chmod 0755 /etc/letsencrypt/renewal-hooks/deploy/stalwart.sh

echo "==> Enabling and starting Stalwart"
systemctl daemon-reload
systemctl enable --now stalwart-mail

echo "==> Waiting for SMTP listener"
for i in {1..60}; do
  if ss -lntp | grep -q ':25 '; then
    break
  fi
  sleep 2
done

echo "==> Waiting for IMAPS listener"
for i in {1..60}; do
  if ss -lntp | grep -q ':993 '; then
    break
  fi
  sleep 2
done

echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d /etc/fail2ban/filter.d

cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN_SSH'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN_SSH

cat > /etc/fail2ban/filter.d/stalwart-auth.conf <<'F2B'
[Definition]
failregex = ^.* (smtp|imap) .* auth.* failed .* remoteIp=<HOST>.*$
            ^.* authentication failed .* remote-ip=<HOST>.*$
ignoreregex =
F2B

cat > /etc/fail2ban/jail.d/stalwart.local <<'FAIL2BAN_S'
[stalwart-auth]
enabled = true
filter = stalwart-auth
backend = systemd
journalmatch = _SYSTEMD_UNIT=stalwart-mail.service
maxretry = 6
findtime = 10m
bantime = 24h
banaction = iptables-multiport
port = smtp,submission,smtps,imaps
FAIL2BAN_S

systemctl enable --now fail2ban

echo "==> Final package update"
dnf -y update

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r
echo
echo "SELinux:"
getenforce || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(25|443|465|587|993|4190|8080)\b' || true
echo
echo "Services:"
systemctl is-active stalwart-mail nginx fail2ban chronyd || true
echo
echo "Web/Admin UI:"
echo "https://${MAIL_HOSTNAME}/"
echo "Admin user:     admin"
echo "Admin password: $(cat /root/.stalwart_admin_password)"
echo
echo "Next: in the admin UI, add the mail domain (${PRIMARY_DOMAIN}), then generate a DKIM key"
echo "for it from Settings > DKIM. Stalwart will show the exact TXT record (selector default)"
echo "to publish at default._domainkey.${PRIMARY_DOMAIN}."
echo
echo "Suggested DNS:"
echo "  A     ${MAIL_HOSTNAME}              -> <this server IP>"
echo "  MX    ${PRIMARY_DOMAIN}             -> ${MAIL_HOSTNAME}"
echo "  TXT   ${PRIMARY_DOMAIN}             -> v=spf1 mx ~all"
echo "  TXT   _dmarc.${PRIMARY_DOMAIN}      -> v=DMARC1; p=none; rua=mailto:dmarc@${PRIMARY_DOMAIN}"
echo
echo "Final step: confirm rDNS (PTR) for the public IP resolves to ${MAIL_HOSTNAME}"

Make it executable and run it:

chmod 700 /root/setup-stalwart-almalinux9.sh
MAIL_HOSTNAME=mail.example.com \
PRIMARY_DOMAIN=example.com \
LETSENCRYPT_EMAIL=ops@example.com \
/root/setup-stalwart-almalinux9.sh

The bootstrap admin password is written to /root/.stalwart_admin_password. Log into the web admin at https://mail.example.com/, add example.com as a mail domain, generate the DKIM key from Settings > DKIM, copy the TXT record verbatim into DNS, then create the first mailbox. Send a test to a Gmail-verified address and confirm Authentication-Results shows spf=pass dkim=pass dmarc=pass. Hold DMARC at p=none for two weeks while reading aggregate reports, then escalate. The script intentionally does not configure host-level backups — assume VM-level snapshots; on bare metal, add a daily restic step covering /opt/stalwart/data (the RocksDB store) and /opt/stalwart/etc.

Stalwart’s single-binary footprint cuts a lot of operational surface, but the perimeter — DNS, rDNS, DKIM rotation, deliverability monitoring — is still where mail servers go wrong. Stack Harbor runs Stalwart with monitoring and support wired in, so deliverability drift gets caught while it is still fixable rather than after Gmail starts bouncing. If you want to scope the work, start the conversation here.