Skip to content

Deploying Mautic marketing automation on Ubuntu 22.04 (production-ready)

Stand up a hardened self-hosted Mautic 5 on Ubuntu 22.04 — MariaDB + PHP 8.1 + nginx + Let's Encrypt, queue workers, segment cron, S3-compatible asset storage.

You install Mautic, point it at a database, ship the first nurture campaign. The web wizard says everything is green. Two weeks later the marketing team complains that emails are going out hours late, that contacts who unsubscribed are still receiving messages, and that the campaign builder is timing out on save. None of this is a Mautic bug. Mautic in production is a PHP application, a database, three independent cron jobs, and a queue — and a stock mautic:run per-minute crontab cannot keep up beyond a few thousand contacts. The defaults are tuned for a demo, not for sending segmented campaigns at 50,000-contact scale.

What’s happening

A Mautic install that holds up under real load needs: PHP 8.1 with the right extensions and OPcache tuned for production; MariaDB 10.11 with innodb_buffer_pool_size raised to match the contact volume; nginx terminating TLS, serving static assets directly, and proxying PHP-FPM over a Unix socket; cron split into three jobs — mautic:segments:update, mautic:campaigns:update, mautic:campaigns:trigger — running every minute under a service account; a separate mautic:emails:send queue worker so the actual outbound MTA traffic does not block segment evaluation; an SMTP relay (Postal, SES, or a dedicated MTA) that signs DKIM as the correct d= for the campaign sender domain; and S3-compatible storage for the media library so backups and load-balancer rollouts don’t have to drag a stateful /media around. The admin panel must be behind nginx with TLS and rate-limited login attempts; Mautic’s bundled auth is not strong enough to face the open internet without fail2ban watching the access log.

How to verify

After install, the host listeners should be:

ss -lntp | grep -E ':(80|443|3306)\b'
# 0.0.0.0:80     nginx
# 0.0.0.0:443    nginx
# 127.0.0.1:3306 mariadbd

MariaDB bound to localhost only; nothing else exposed beyond HTTPS. PHP-FPM should be on a Unix socket, not a TCP port:

ls -l /run/php/php8.1-fpm-mautic.sock

Verify the cron jobs are actually running and converging:

sudo -u mautic crontab -l
journalctl -u mautic-queue --since "10 minutes ago" | tail -20

Confirm the admin UI presents the Let’s Encrypt cert:

curl -sI https://mautic.example.com/ | head -5

If mautic:campaigns:trigger does not appear in the crontab, contacts will enter campaigns but no action will fire — every email becomes silently queued and never sent.

The fix

Save the script below as /root/setup-mautic-ubuntu22.sh, then run it. It performs the full installer flow on a fresh Ubuntu 22.04 VM: apt update, kernel/network tuning, file limits, hardens SSH while keeping root key access, configures UFW with only SSH/HTTP/HTTPS open, installs MariaDB 10.11 bound to localhost, installs PHP 8.1 with the required extensions and a production php.ini plus OPcache settings, installs nginx and Composer, creates the mautic service user, downloads the latest Mautic 5 via Composer, writes local.php with database and S3 (MinIO/Spaces/SES-S3) credentials, runs the install command non-interactively, writes the three cron jobs under the mautic user, writes a systemd unit for the email-send queue worker with LimitNOFILE=64000, provisions Let’s Encrypt, and configures fail2ban for SSH and Mautic admin login.

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

### Ubuntu 22.04 Mautic 5 marketing automation clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs MariaDB + PHP 8.1 + nginx + Let's Encrypt + Composer-installed Mautic 5
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${MAUTIC_HOSTNAME:?Set MAUTIC_HOSTNAME, e.g. mautic.example.com}"
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL}"
: "${SMTP_HOST:?Set SMTP_HOST, e.g. send.example.com}"
: "${SMTP_PORT:=587}"
: "${SMTP_USERNAME:?Set SMTP_USERNAME for the relay}"
: "${SMTP_PASSWORD:?Set SMTP_PASSWORD for the relay}"
: "${SMTP_FROM:?Set SMTP_FROM, e.g. campaigns@mailings.example.com}"
: "${S3_ENDPOINT:?Set S3_ENDPOINT, e.g. https://nyc3.digitaloceanspaces.com}"
: "${S3_BUCKET:?Set S3_BUCKET}"
: "${S3_REGION:=us-east-1}"
: "${S3_ACCESS_KEY:?Set S3_ACCESS_KEY}"
: "${S3_SECRET_KEY:?Set S3_SECRET_KEY}"
: "${TIMEZONE:=America/Toronto}"

export DEBIAN_FRONTEND=noninteractive

echo
echo "========================================"
echo "Mautic Ubuntu 22.04 Setup"
echo "Hostname: ${MAUTIC_HOSTNAME}"
echo "========================================"
echo

echo "==> Updating base OS"
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget gnupg ca-certificates chrony \
  fail2ban unattended-upgrades \
  lsof tcpdump dnsutils \
  ufw jq git unzip \
  apt-transport-https software-properties-common

timedatectl set-ntp true
timedatectl set-timezone "${TIMEZONE}"

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-mautic.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.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
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-mautic.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 UFW"
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
yes | ufw enable

echo "==> Configuring unattended-upgrades for security only"
cat > /etc/apt/apt.conf.d/52unattended-upgrades-local <<'UA'
Unattended-Upgrade::Allowed-Origins {
  "${distro_id}:${distro_codename}-security";
  "${distro_id}ESMApps:${distro_codename}-apps-security";
  "${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::Automatic-Reboot "false";
UA
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AAU'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AAU

echo "==> Installing MariaDB 10.11 (localhost-bound)"
curl -fsSL https://mariadb.org/mariadb_release_signing_key.pgp \
  | gpg --dearmor -o /usr/share/keyrings/mariadb-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/mariadb-archive-keyring.gpg] https://mirror.its.dal.ca/mariadb/repo/10.11/ubuntu jammy main" \
  > /etc/apt/sources.list.d/mariadb.list
apt-get update
apt-get -y install mariadb-server mariadb-client

cat > /etc/mysql/mariadb.conf.d/99-mautic.cnf <<'MARIADB'
[mysqld]
bind-address = 127.0.0.1
max_connections = 400
max_allowed_packet = 256M
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
MARIADB
systemctl restart mariadb

MAUTIC_DB_PASSWORD="$(openssl rand -hex 24)"
mysql --protocol=socket -uroot <<SQL
CREATE DATABASE IF NOT EXISTS mautic CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'mautic'@'127.0.0.1' IDENTIFIED BY '${MAUTIC_DB_PASSWORD}';
GRANT ALL ON mautic.* TO 'mautic'@'127.0.0.1';
FLUSH PRIVILEGES;
SQL

echo "==> Installing PHP 8.1 + extensions"
add-apt-repository -y ppa:ondrej/php
apt-get update
apt-get -y install \
  php8.1-cli php8.1-fpm \
  php8.1-mysql php8.1-curl php8.1-xml php8.1-mbstring \
  php8.1-zip php8.1-bcmath php8.1-intl php8.1-gd \
  php8.1-imap php8.1-ldap php8.1-redis

cat > /etc/php/8.1/fpm/conf.d/99-mautic.ini <<'PHPINI'
memory_limit = 1024M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 240
date.timezone = America/Toronto

opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0
opcache.save_comments = 1
opcache.fast_shutdown = 1
PHPINI

cat > /etc/php/8.1/fpm/pool.d/mautic.conf <<'PHPFPM'
[mautic]
user = mautic
group = mautic
listen = /run/php/php8.1-fpm-mautic.sock
listen.owner = www-data
listen.group = www-data
pm = dynamic
pm.max_children = 40
pm.start_servers = 6
pm.min_spare_servers = 4
pm.max_spare_servers = 10
pm.max_requests = 500
request_terminate_timeout = 300s
catch_workers_output = yes
PHPFPM

# Disable the default pool
rm -f /etc/php/8.1/fpm/pool.d/www.conf

echo "==> Creating mautic service user"
id -u mautic >/dev/null 2>&1 || useradd --system --home /var/www/mautic --shell /bin/bash mautic
install -d -o mautic -g mautic /var/www/mautic

echo "==> Installing Composer"
curl -fsSL https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

echo "==> Installing Mautic 5 via Composer"
sudo -u mautic -H bash -c "
  cd /var/www/mautic
  composer create-project mautic/recommended-project:^5 . --no-interaction --no-dev --prefer-dist
"

install -d -o mautic -g mautic /var/www/mautic/var/log /var/www/mautic/var/cache /var/www/mautic/docroot/media

echo "==> Writing config/local.php"
INSTALL_KEY="$(openssl rand -hex 16)"
MAUTIC_ADMIN_PASSWORD="$(openssl rand -hex 16 | tee /root/.mautic_admin_password)"
cat > /var/www/mautic/config/local.php <<PHP
<?php
\$parameters = [
    'db_driver' => 'pdo_mysql',
    'db_host' => '127.0.0.1',
    'db_table_prefix' => null,
    'db_port' => 3306,
    'db_name' => 'mautic',
    'db_user' => 'mautic',
    'db_password' => '${MAUTIC_DB_PASSWORD}',

    'mailer_dsn' => 'smtp://${SMTP_USERNAME}:${SMTP_PASSWORD}@${SMTP_HOST}:${SMTP_PORT}',
    'mailer_from_email' => '${SMTP_FROM}',
    'mailer_from_name' => 'Marketing',
    'mailer_spool_type' => 'memory',

    'messenger_dsn_email' => 'doctrine://default?queue_name=email',

    'site_url' => 'https://${MAUTIC_HOSTNAME}',
    'secret_key' => '${INSTALL_KEY}',
    'cache_path' => '%kernel.project_dir%/var/cache',
    'log_path'   => '%kernel.project_dir%/var/log',
    'tmp_path'   => '%kernel.project_dir%/var/tmp',

    'rememberme_key' => '${INSTALL_KEY}',
    'image_path' => 'media/images',

    'mautic_install_source' => 'docker',

    // S3-compatible asset storage
    'aws_endpoint' => '${S3_ENDPOINT}',
    'aws_region' => '${S3_REGION}',
    'aws_bucket' => '${S3_BUCKET}',
    'aws_key' => '${S3_ACCESS_KEY}',
    'aws_secret' => '${S3_SECRET_KEY}',
];
PHP

chown mautic:mautic /var/www/mautic/config/local.php
chmod 640 /var/www/mautic/config/local.php

echo "==> Running Mautic install command"
sudo -u mautic -H bash -c "
  cd /var/www/mautic
  php bin/console mautic:install \
    https://${MAUTIC_HOSTNAME} \
    --db_driver=pdo_mysql --db_host=127.0.0.1 --db_port=3306 \
    --db_name=mautic --db_user=mautic --db_password='${MAUTIC_DB_PASSWORD}' \
    --admin_email='${LETSENCRYPT_EMAIL}' --admin_password='${MAUTIC_ADMIN_PASSWORD}' \
    --admin_firstname=Admin --admin_lastname=User \
    --no-interaction
"

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

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

server {
    listen 443 ssl http2;
    server_name ${MAUTIC_HOSTNAME};
    root /var/www/mautic/docroot;
    index index.php;

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

    client_max_body_size 64m;

    location / {
        try_files \$uri /index.php\$is_args\$args;
    }

    location ~ ^/index\.php(/|\$) {
        fastcgi_pass unix:/run/php/php8.1-fpm-mautic.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)\$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT \$realpath_root;
        fastcgi_read_timeout 300s;
    }

    location ~ \.php\$ { return 404; }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)\$ {
        expires 30d;
        access_log off;
    }
}
NGINX

mkdir -p /var/www/html
ln -sf /etc/nginx/sites-available/mautic.conf /etc/nginx/sites-enabled/mautic.conf
rm -f /etc/nginx/sites-enabled/default
systemctl enable --now php8.1-fpm nginx
certbot --nginx -n --agree-tos -m "${LETSENCRYPT_EMAIL}" -d "${MAUTIC_HOSTNAME}"
systemctl reload nginx

echo "==> Writing Mautic crontab (segments + campaigns + triggers)"
crontab -u mautic - <<'CRON'
* * * * * /usr/bin/php /var/www/mautic/bin/console mautic:segments:update --no-interaction >/dev/null 2>&1
* * * * * /usr/bin/php /var/www/mautic/bin/console mautic:campaigns:update --no-interaction >/dev/null 2>&1
* * * * * /usr/bin/php /var/www/mautic/bin/console mautic:campaigns:trigger --no-interaction >/dev/null 2>&1
*/15 * * * * /usr/bin/php /var/www/mautic/bin/console mautic:import --no-interaction >/dev/null 2>&1
*/15 * * * * /usr/bin/php /var/www/mautic/bin/console mautic:emails:fetch --no-interaction >/dev/null 2>&1
CRON

echo "==> Writing systemd unit for the email-send queue worker"
cat > /etc/systemd/system/mautic-queue.service <<'UNIT'
[Unit]
Description=Mautic email send queue worker
After=network-online.target mariadb.service
Wants=network-online.target

[Service]
Type=simple
User=mautic
Group=mautic
WorkingDirectory=/var/www/mautic
ExecStart=/usr/bin/php bin/console messenger:consume email --time-limit=3600 --memory-limit=512M
Restart=always
RestartSec=10
LimitNOFILE=64000
ProtectSystem=full
ProtectHome=true
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable --now mautic-queue

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/mautic-auth.conf <<'F2B'
[Definition]
failregex = ^.*"POST /s/login_check HTTP/[\d.]+" 401 .* \[client <HOST>\]$
            ^.*"POST /s/login_check HTTP/[\d.]+" 302 .* \[client <HOST>\].*Invalid credentials$
ignoreregex =
F2B

cat > /etc/fail2ban/jail.d/mautic.local <<'FAIL2BAN_M'
[mautic-auth]
enabled = true
filter = mautic-auth
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 10m
bantime = 24h
banaction = iptables-multiport
port = http,https
FAIL2BAN_M

systemctl enable --now fail2ban

echo "==> Final package update"
apt-get update
apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|3306)\b' || true
echo
echo "Services:"
systemctl is-active mariadb php8.1-fpm nginx mautic-queue fail2ban || true
echo
echo "Cron (mautic):"
crontab -u mautic -l || true
echo
echo "Web UI:"
echo "https://${MAUTIC_HOSTNAME}/"
echo "Admin email:    ${LETSENCRYPT_EMAIL}"
echo "Admin password: $(cat /root/.mautic_admin_password)"
echo
echo "Relay configured: ${SMTP_HOST}:${SMTP_PORT}"
echo "From address:     ${SMTP_FROM}"
echo "Asset storage:    s3://${S3_BUCKET} via ${S3_ENDPOINT}"
echo
echo "Suggested DNS for the sender subdomain mirrors the Listmonk guide."
echo
echo "Next: in Configuration > Email Settings, confirm the SMTP transport saves and"
echo "test-send to a Gmail-verified address. Confirm Authentication-Results shows pass."

Make it executable and run it:

chmod 700 /root/setup-mautic-ubuntu22.sh
MAUTIC_HOSTNAME=mautic.example.com \
LETSENCRYPT_EMAIL=ops@example.com \
SMTP_HOST=send.example.com \
SMTP_USERNAME=MauticCampaigns \
SMTP_PASSWORD=<postal-credential> \
SMTP_FROM=campaigns@mailings.example.com \
S3_ENDPOINT=https://nyc3.digitaloceanspaces.com \
S3_BUCKET=mautic-assets \
S3_ACCESS_KEY=... \
S3_SECRET_KEY=... \
/root/setup-mautic-ubuntu22.sh

The admin password is written to /root/.mautic_admin_password. After login, visit Configuration > Email Settings, save the form once (this rewrites the cached configuration), and send a test to a Gmail-verified address. Visit Maintenance > Cron and confirm all three jobs reported “OK” in the last minute — if not, the crontab did not pick up. Walk every campaign through a small test segment of internal addresses before turning it on for the production list. The script intentionally does not configure host-level backups — assume VM-level snapshots; on bare metal, add a daily mysqldump mautic and a restic step targeting the S3 bucket if you want cross-region durability.

Marketing automation that converges instead of drifting takes weekly attention to bounces, list health, and campaign deliverability. Stack Harbor runs Mautic as part of environment management with the cron, the queue, and the SMTP relay on the same monitoring footing as production application traffic.