Skip to content

Deploying Mailcow on AlmaLinux 9 (production-ready)

Stand up a hardened Mailcow Dockerized mail server on AlmaLinux 9 — Postfix + Dovecot + rspamd + SOGo behind nginx, Let's Encrypt, SPF/DKIM/DMARC, fail2ban.

You stand up Mailcow on a clean VM, docker compose up -d returns happy, you send a test through SOGo, it reaches Gmail’s inbox, you hand it over. Three weeks later the same domain is bouncing at Gmail with 550 5.7.26 and Outlook has stopped accepting anything. The MTA is fine. What drifted is the perimeter around it — PTR was never set, the SPF record forgot the new IP, the DKIM selector in DNS doesn’t match the one rspamd is signing with, and fail2ban was never wired to the rspamd logs so a brute-force pass against SMTP AUTH burned the IP’s reputation overnight.

What’s happening

A Mailcow box that is actually production-ready needs more than docker compose up. The host needs ports 25, 80, 443, 465, 587, 993 and 4190 reachable; nothing should be listening on 25 other than the Mailcow Postfix container (no postfix package, no sendmail on the host). The hostname must have a forward and a matching reverse — mail.example.com resolves to the IP, and the IP’s PTR resolves back to mail.example.com, or every receiver downgrades the message. SPF must list this server, DKIM keys generated by rspamd must be published verbatim in DNS, DMARC must start at p=none with a rua= you actually monitor, and MTA-STS plus TLS-RPT must exist so receivers don’t silently fall back to plaintext on TLS handshake failures. fail2ban has to watch the Mailcow logs, not just the host’s SSH log. None of these are individually load-bearing. Skip them and Gmail will tell you about it.

How to verify

After install, the listeners on the host should look like this:

ss -lntp | grep -E ':(25|80|443|465|587|993|4190)\b'
# 0.0.0.0:25   docker-proxy
# 0.0.0.0:80   docker-proxy
# 0.0.0.0:443  docker-proxy
# 0.0.0.0:465  docker-proxy
# 0.0.0.0:587  docker-proxy
# 0.0.0.0:993  docker-proxy
# 0.0.0.0:4190 docker-proxy

DNS and PTR alignment:

dig +short MX example.com
dig +short A mail.example.com
dig +short -x <your-ip>
# all three must resolve consistently

STARTTLS on submission and the cert chain 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='

Both must present the Let’s Encrypt cert for mail.example.com, not the Mailcow self-signed default. If either does, the ACME hook never ran.

The fix

Save the script below as /root/setup-mailcow-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 fail2ban for SSH and for the Mailcow Postfix/Dovecot/SOGo logs, enables dnf-automatic.timer for security updates, installs Docker CE + compose plugin from the upstream repo, clones the official Mailcow repository, runs generate_config.sh non-interactively for mail.example.com, brings the stack up, waits for each listener to come up, and prints the DKIM TXT record at the end for DNS publication.

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

### AlmaLinux 9.x Mailcow Dockerized clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs Docker CE + compose plugin
### Clones official mailcow-dockerized and brings the stack up
### 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}"
: "${TIMEZONE:=America/Toronto}"

echo
echo "========================================"
echo "Mailcow AlmaLinux 9.x Setup"
echo "Hostname: ${MAIL_HOSTNAME}"
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 \
  yum-utils \
  tar \
  gzip \
  unzip \
  git \
  jq \
  iproute \
  net-tools

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-mailcow.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
net.ipv6.conf.default.accept_redirects = 0

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
fs.inotify.max_user_instances = 8192
fs.inotify.max_user_watches = 524288
SYSCTL

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

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-mailcow.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 "==> Installing Docker CE + compose plugin"
dnf -y install dnf-plugins-core
dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker

echo "==> Cloning mailcow-dockerized"
umask 022
cd /opt
if [[ ! -d /opt/mailcow-dockerized ]]; then
  git clone https://github.com/mailcow/mailcow-dockerized.git
fi
cd /opt/mailcow-dockerized

echo "==> Generating mailcow.conf non-interactively"
export MAILCOW_HOSTNAME="${MAIL_HOSTNAME}"
export MAILCOW_TZ="${TIMEZONE}"
export MAILCOW_BRANCH=master
yes "" | ./generate_config.sh || true

if grep -q '^MAILCOW_HOSTNAME=$' mailcow.conf || ! grep -q '^MAILCOW_HOSTNAME=' mailcow.conf; then
  sed -i "s|^MAILCOW_HOSTNAME=.*|MAILCOW_HOSTNAME=${MAIL_HOSTNAME}|" mailcow.conf
fi

# Bind admin UI to nginx-only (host port 443 / 80) and disable the legacy SOLR
sed -i 's|^HTTP_PORT=.*|HTTP_PORT=80|' mailcow.conf
sed -i 's|^HTTPS_PORT=.*|HTTPS_PORT=443|' mailcow.conf
sed -i 's|^SKIP_SOLR=.*|SKIP_SOLR=y|' mailcow.conf
sed -i 's|^ACME_CONTACT=.*|ACME_CONTACT=postmaster@example.com|' mailcow.conf

echo "==> Pulling images"
docker compose pull

echo "==> Bringing the stack up"
docker compose up -d

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 HTTPS listener"
for i in {1..60}; do
  if ss -lntp | grep -q ':443 '; then
    break
  fi
  sleep 2
done

echo "==> Configuring fail2ban for SSH and Mailcow logs"
mkdir -p /etc/fail2ban/jail.d
mkdir -p /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/mailcow-postfix.conf <<'F2B_POSTFIX'
[Definition]
failregex = warning: [-._\w]+\[<HOST>\]: SASL [A-Z]+ authentication failed
ignoreregex =
F2B_POSTFIX

cat > /etc/fail2ban/jail.d/mailcow.local <<'FAIL2BAN_MAILCOW'
[mailcow-postfix]
enabled = true
filter = mailcow-postfix
logpath = /var/lib/docker/volumes/mailcowdockerized_postfix-vol-1/_data/mail.log
maxretry = 6
findtime = 10m
bantime = 24h
banaction = iptables-multiport
port = smtp,submission,smtps
FAIL2BAN_MAILCOW

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|80|443|465|587|993|4190)\b' || true
echo
echo "Mailcow containers:"
cd /opt/mailcow-dockerized && docker compose ps
echo
echo "DKIM selector dkim public key (paste as TXT for dkim._domainkey.example.com):"
docker exec $(docker ps --filter name=rspamd-mailcow --format '{{.Names}}') \
  rspamadm dkim_keygen -s dkim -d "${MAIL_HOSTNAME#mail.}" -b 2048 -k /tmp/_dkim_show.key 2>&1 | tail -n +1 || true
echo
echo "Web UI:"
echo "https://${MAIL_HOSTNAME}/"
echo "Default admin login: admin / moohoo (change immediately)"
echo
echo "Suggested DNS:"
echo "  A     ${MAIL_HOSTNAME}                -> <this server IP>"
echo "  MX    example.com                     -> ${MAIL_HOSTNAME}"
echo "  TXT   example.com                     -> v=spf1 mx ~all"
echo "  TXT   _dmarc.example.com              -> v=DMARC1; p=none; rua=mailto:dmarc@example.com"
echo "  TXT   _mta-sts.example.com            -> v=STSv1; id=$(date +%Y%m%d01)"
echo "  TXT   _smtp._tls.example.com          -> v=TLSRPTv1; rua=mailto:tlsrpt@example.com"
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-mailcow-almalinux9.sh
MAIL_HOSTNAME=mail.example.com /root/setup-mailcow-almalinux9.sh

After the script finishes, log into the Mailcow admin UI, add the mail domain, and let it generate its own DKIM key from the Configuration > ARC/DKIM panel — paste the resulting selector record into DNS verbatim. Hold DMARC at p=none for two weeks while you read aggregate reports, then move to p=quarantine, then p=reject. The script intentionally does not configure host-level backups — the assumption is VM snapshots at the cloud layer; on bare metal, add restic covering /opt/mailcow-dockerized and the named Docker volumes.

Mail infrastructure drifts the moment nobody is looking at deliverability reports. Stack Harbor runs Mailcow as part of deployment management with monitoring against the major receiver feedback loops.