Skip to content

Deploying a MariaDB Galera 3-node cluster on AlmaLinux 9

Stand up a self-hosted MariaDB 10.11 Galera cluster on AlmaLinux 9 — TLS-encrypted gcomm, HAProxy frontend, garbd arbitrator on a fourth host.

You inherit a stack where the database is “replicated” — but what that actually means is a primary MariaDB with a single async replica, no automatic failover, and an application that writes through a DNS name nobody can move quickly. The first time the primary loses storage during peak hours, the replica is forty seconds behind, the app retries against a read-only server for ten minutes before someone notices, and the post-incident review writes “investigate Galera” on the action items. Then the action item sits in a backlog for a quarter. Here is the actual installer for the day you decide to stop deferring.

What’s happening

A MariaDB Galera cluster is not master-replica. All three nodes accept writes and stay in sync through certification-based replication: every write set is broadcast to every node, each node certifies it against pending transactions, and either every node commits or every node aborts. The wire protocol is gcomm — a group communication layer that handles flow control, quorum, and node-join coordination. Three is the smallest production cluster size because two nodes can’t form quorum after one fails; if you can’t afford a third full data node, you run two data nodes plus a garbd arbitrator on a third small host that votes but holds no data. In front, HAProxy presents a single VIP and clustercheck (a tiny xinetd-served script on each node) tells HAProxy which member is wsrep_local_state=4 (Synced) and therefore eligible to receive writes. Skip the arbitrator and a one-node failure on a two-node cluster halts both. Skip the load balancer and the application keeps a TCP connection open to a node that went non-primary five minutes ago.

How to verify

From any node:

mysql -uroot -p -e "SHOW STATUS LIKE 'wsrep_cluster_size';"
# Expect: 3 on a healthy 3-node cluster, 4 if the arbitrator is counted
mysql -uroot -p -e "SHOW STATUS LIKE 'wsrep_cluster_status';"
# Expect: Primary
mysql -uroot -p -e "SHOW STATUS LIKE 'wsrep_local_state_comment';"
# Expect: Synced

Flow-control pressure — if wsrep_flow_control_paused climbs above 0.10 sustained, one node can’t keep up and is back-pressuring the others:

mysql -uroot -p -e "SHOW STATUS LIKE 'wsrep_flow_control_paused';"

HAProxy backend health:

echo "show stat" | socat stdio /run/haproxy/admin.sock | awk -F, '$1=="galera_write"'

You should see exactly one server marked UP (the write-leader policy is “first-available”; reads can spread across all three).

The fix

Save as /root/setup-galera-node.sh. Run on each of the three data nodes after editing the header. The first node to be bootstrapped runs with --wsrep-new-cluster once — the script handles that automatically when BOOTSTRAP=yes is set. The other two nodes join in sequence.

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

### AlmaLinux 9 — MariaDB 10.11 Galera 3-node cluster
### + HAProxy frontend, clustercheck health endpoint, TLS on gcomm
### Run on each node after editing variables; bootstrap the first one only

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

# === EDIT PER NODE ===
NODE_NAME="db01"               # db01 / db02 / db03
NODE_IP="10.20.0.11"           # this node's private IP
PEER_IPS=("10.20.0.11" "10.20.0.12" "10.20.0.13")
PEER_NAMES=("db01" "db02" "db03")
CLUSTER_NAME="galera_prod"
ROOT_PASSWORD="CHANGE_ME_ROOT"
SST_PASSWORD="CHANGE_ME_SST"
CHECK_PASSWORD="CHANGE_ME_CHECK"
BOOTSTRAP="no"                  # set to "yes" on the first node only
# =====================

echo
echo "========================================"
echo "Galera node ${NODE_NAME} (${NODE_IP})"
echo "Bootstrap=${BOOTSTRAP}"
echo "========================================"
echo

echo "==> Base OS update"
dnf -y update
dnf -y install epel-release
dnf -y install vim curl wget chrony fail2ban dnf-automatic \
  policycoreutils-python-utils lsof tcpdump bind-utils tar gzip \
  iproute net-tools jq socat rsync xinetd nmap-ncat \
  openssl-perl

systemctl enable --now chronyd

echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true

echo "==> Sysctl tuning"
cat > /etc/sysctl.d/99-galera.conf <<'SYSCTL'
vm.swappiness = 1
vm.overcommit_memory = 2
vm.overcommit_ratio = 90
vm.dirty_background_ratio = 3
vm.dirty_ratio = 10
fs.file-max = 2097152
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
SYSCTL
sysctl --system

cat > /etc/security/limits.d/99-mysql.conf <<'LIMITS'
mysql soft nofile 200000
mysql hard nofile 200000
mysql soft nproc 65535
mysql hard nproc 65535
LIMITS

echo "==> SSH lockdown"
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

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

cat > /etc/dnf/automatic.conf <<'DA'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
DA
systemctl enable --now dnf-automatic.timer

echo "==> MariaDB 10.11 repo"
cat > /etc/yum.repos.d/MariaDB.repo <<'REPO'
[mariadb]
name = MariaDB-10.11
baseurl = https://rpm.mariadb.org/10.11/rhel/$releasever/$basearch
module_hotfixes = 1
gpgkey = https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck = 1
REPO

dnf -y install MariaDB-server MariaDB-client MariaDB-backup galera-4

echo "==> Generating cluster TLS material"
mkdir -p /etc/mysql/tls
cd /etc/mysql/tls

if [[ ! -f ca.pem ]]; then
  openssl genrsa -out ca-key.pem 4096
  openssl req -x509 -new -nodes -key ca-key.pem -days 3650 \
    -subj "/CN=galera-ca" -out ca.pem
fi

openssl genrsa -out node-key.pem 4096
openssl req -new -key node-key.pem -subj "/CN=${NODE_NAME}" -out node.csr
openssl x509 -req -in node.csr -CA ca.pem -CAkey ca-key.pem \
  -CAcreateserial -out node-cert.pem -days 730 -sha256

chown -R mysql:mysql /etc/mysql/tls
chmod 600 /etc/mysql/tls/*-key.pem
chmod 644 /etc/mysql/tls/*.pem
cd /

echo "==> Note: copy /etc/mysql/tls/ca.pem + ca-key.pem to peers before they bootstrap"
echo "==> (using the SAME CA across the cluster — each node generates its own cert under that CA)"

echo "==> Writing my.cnf"
cat > /etc/my.cnf.d/galera.cnf <<EOF
[mysqld]
bind-address                   = 0.0.0.0
default-storage-engine         = innodb
binlog_format                  = ROW
innodb_autoinc_lock_mode       = 2
innodb_doublewrite             = 1
innodb_flush_log_at_trx_commit = 2
innodb_buffer_pool_size        = 4G
innodb_log_file_size           = 512M
innodb_file_per_table          = 1
max_connections                = 1000
table_open_cache               = 4000
performance_schema             = ON

# === wsrep ===
wsrep_on                       = ON
wsrep_provider                 = /usr/lib64/galera-4/libgalera_smm.so
wsrep_cluster_name             = ${CLUSTER_NAME}
wsrep_cluster_address          = gcomm://${PEER_IPS[0]},${PEER_IPS[1]},${PEER_IPS[2]}
wsrep_node_name                = ${NODE_NAME}
wsrep_node_address             = ${NODE_IP}
wsrep_sst_method               = mariabackup
wsrep_sst_auth                 = sstuser:${SST_PASSWORD}
wsrep_slave_threads            = 8

# TLS on the gcomm channel + SST
wsrep_provider_options="socket.ssl=yes;socket.ssl_cert=/etc/mysql/tls/node-cert.pem;socket.ssl_key=/etc/mysql/tls/node-key.pem;socket.ssl_ca=/etc/mysql/tls/ca.pem;gcache.size=2G"

[mariabackup]
user                           = sstuser
password                       = ${SST_PASSWORD}

[sst]
encrypt                        = 4
tcert                          = /etc/mysql/tls/node-cert.pem
tkey                           = /etc/mysql/tls/node-key.pem
tca                            = /etc/mysql/tls/ca.pem

[client]
ssl-ca                         = /etc/mysql/tls/ca.pem
EOF

systemctl daemon-reload

echo "==> Starting MariaDB"
if [[ "${BOOTSTRAP}" == "yes" ]]; then
  echo "==> BOOTSTRAPPING new cluster (this node only)"
  galera_new_cluster
else
  systemctl enable --now mariadb
fi

echo "==> Securing local root + creating SST/check users"
mysql -uroot <<SQL
ALTER USER 'root'@'localhost' IDENTIFIED BY '${ROOT_PASSWORD}';
DELETE FROM mysql.global_priv WHERE User='';
DROP DATABASE IF EXISTS test;
CREATE USER IF NOT EXISTS 'sstuser'@'localhost' IDENTIFIED BY '${SST_PASSWORD}';
GRANT PROCESS, RELOAD, LOCK TABLES, REPLICATION CLIENT, BINLOG MONITOR, BACKUP_ADMIN ON *.* TO 'sstuser'@'localhost';
CREATE USER IF NOT EXISTS 'clustercheck'@'localhost' IDENTIFIED BY '${CHECK_PASSWORD}';
GRANT PROCESS ON *.* TO 'clustercheck'@'localhost';
FLUSH PRIVILEGES;
SQL

systemctl enable mariadb

echo "==> clustercheck via xinetd on port 9200"
cat > /usr/local/bin/clustercheck <<CHK
#!/usr/bin/env bash
MYSQL_USERNAME="clustercheck"
MYSQL_PASSWORD="${CHECK_PASSWORD}"
ERR_FILE="\${ERR_FILE:-/dev/null}"
AVAILABLE_WHEN_DONOR="\${AVAILABLE_WHEN_DONOR:-0}"
AVAILABLE_WHEN_READONLY="\${AVAILABLE_WHEN_READONLY:-0}"

WSREP_STATUS=\$(mysql -u\${MYSQL_USERNAME} -p\${MYSQL_PASSWORD} -Bse "SHOW STATUS LIKE 'wsrep_local_state';" 2>"\${ERR_FILE}" | awk '{print \$2}')
READ_ONLY=\$(mysql -u\${MYSQL_USERNAME} -p\${MYSQL_PASSWORD} -Bse "SHOW VARIABLES LIKE 'read_only';" 2>"\${ERR_FILE}" | awk '{print \$2}')

if [[ "\${WSREP_STATUS}" == "4" ]] || ( [[ "\${WSREP_STATUS}" == "2" ]] && [[ "\${AVAILABLE_WHEN_DONOR}" == "1" ]] ); then
  if [[ "\${READ_ONLY}" == "ON" ]] && [[ "\${AVAILABLE_WHEN_READONLY}" == "0" ]]; then
    printf "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: 36\r\n\r\nGalera cluster node is read-only.\r\n\r\n"
    exit 1
  fi
  printf "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 40\r\n\r\nGalera cluster node is synced.\r\n\r\n"
  exit 0
else
  printf "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: 44\r\n\r\nGalera cluster node is not synced.\r\n\r\n"
  exit 1
fi
CHK
chmod 755 /usr/local/bin/clustercheck

cat > /etc/xinetd.d/mysqlchk <<'XIN'
service mysqlchk
{
    disable         = no
    flags           = REUSE
    socket_type     = stream
    port            = 9200
    wait            = no
    user            = nobody
    server          = /usr/local/bin/clustercheck
    log_on_failure  += USERID
    only_from       = 0.0.0.0/0
    per_source      = UNLIMITED
}
XIN

grep -q '^mysqlchk' /etc/services || echo "mysqlchk        9200/tcp # Galera clustercheck" >> /etc/services

systemctl enable --now xinetd

echo "==> Firewall (gcomm 4567, IST 4568, SST 4444, mysql 3306, check 9200)"
dnf -y install firewalld || true
systemctl enable --now firewalld
firewall-cmd --permanent --add-port=3306/tcp
firewall-cmd --permanent --add-port=4444/tcp
firewall-cmd --permanent --add-port=4567/tcp
firewall-cmd --permanent --add-port=4567/udp
firewall-cmd --permanent --add-port=4568/tcp
firewall-cmd --permanent --add-port=9200/tcp
firewall-cmd --reload

echo "==> Wait for MariaDB listener"
for i in {1..60}; do
  if ss -lnt | awk '{print $4}' | grep -q ':3306$'; then break; fi
  sleep 2
done

echo
echo "========================================"
echo "DONE — ${NODE_NAME}"
echo "========================================"
echo
mysql -uroot -p"${ROOT_PASSWORD}" -e "SHOW STATUS LIKE 'wsrep_cluster_size'; SHOW STATUS LIKE 'wsrep_cluster_status'; SHOW STATUS LIKE 'wsrep_local_state_comment';" || true
echo
echo "Listeners:"
ss -lntp | grep -E ':(3306|4444|4567|4568|9200)\b' || true
echo
echo "Next: bootstrap = no on the remaining nodes; start them with 'systemctl start mariadb'."

After all three data nodes are joined, install the HAProxy frontend on a fourth small host (or a pair of them with keepalived):

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

dnf -y install haproxy
mkdir -p /run/haproxy

cat > /etc/haproxy/haproxy.cfg <<'HAP'
global
  maxconn 4096
  log /dev/log local0
  stats socket /run/haproxy/admin.sock mode 660 level admin

defaults
  log global
  mode tcp
  retries 2
  timeout client 30m
  timeout connect 4s
  timeout server 30m
  timeout check 3s

frontend stats
  bind 0.0.0.0:7000
  mode http
  stats enable
  stats uri /

# Single-writer: first-available — only one server gets writes.
frontend galera_write
  bind 0.0.0.0:3306
  default_backend galera_write_bk

backend galera_write_bk
  balance first
  option httpchk
  http-check send meth GET uri /
  http-check expect status 200
  default-server inter 2s rise 2 fall 2 on-marked-down shutdown-sessions
  server db01 10.20.0.11:3306 check port 9200
  server db02 10.20.0.12:3306 check port 9200 backup
  server db03 10.20.0.13:3306 check port 9200 backup

# Multi-reader: roundrobin across all healthy nodes
frontend galera_read
  bind 0.0.0.0:3307
  default_backend galera_read_bk

backend galera_read_bk
  balance roundrobin
  option httpchk
  http-check send meth GET uri /
  http-check expect status 200
  default-server inter 2s rise 2 fall 2
  server db01 10.20.0.11:3306 check port 9200
  server db02 10.20.0.12:3306 check port 9200
  server db03 10.20.0.13:3306 check port 9200
HAP

systemctl enable --now haproxy

Finally, the garbd arbitrator on a fifth tiny host (or co-located with HAProxy) — it votes for quorum without holding data, which lets you survive losing a data node without losing the cluster:

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

dnf -y install galera-4
mkdir -p /etc/galera

cat > /etc/sysconfig/garb <<'GARB'
GALERA_NODES="10.20.0.11:4567 10.20.0.12:4567 10.20.0.13:4567"
GALERA_GROUP="galera_prod"
GARB_OPTIONS="socket.ssl=yes;socket.ssl_cert=/etc/mysql/tls/node-cert.pem;socket.ssl_key=/etc/mysql/tls/node-key.pem;socket.ssl_ca=/etc/mysql/tls/ca.pem"
LOG_FILE="/var/log/garb.log"
GARB

systemctl enable --now garb

A working cluster reports wsrep_cluster_size = 4 (3 data + 1 arbitrator) and wsrep_cluster_status = Primary on all three data nodes. Run a failure drill before traffic: systemctl stop mariadb on db01, watch HAProxy promote db02 to the active write backend within a few seconds, and confirm new connections land there. Then start db01 back — it should rejoin via IST (incremental state transfer from the gcache) rather than a full SST. If you see SST every time you restart a node, your gcache.size is too small for the volume of writes between restarts.

Run this cluster under Stack Harbor’s Cloud Compute with replication-state monitoring and Sev-1 escalation through our monitoring plane — or start a scoping call and we’ll deploy it for you under environment management.