Skip to content

Deploying Keycloak IAM on AlmaLinux 9 (production-ready)

Stand up a hardened Keycloak IAM on AlmaLinux 9 — PostgreSQL on localhost, systemd unit, nginx reverse proxy with proper forwarded headers, Let's Encrypt TLS.

You’ve been asked to stand up Keycloak as the enterprise IAM. You run kc.sh start-dev, log in as admin/admin, create a realm, wire OIDC into the first app, hand it over. Six months later, the server is still in dev mode, the master realm still has admin/admin, the PostgreSQL instance is bound to 0.0.0.0:5432, the issuer URL is http://localhost:8080/realms/corp in every relying party because hostname-url was never set, and the IAM that every other service trusts is the weakest VM in the fleet.

What’s happening

A Keycloak deployment that is actually production-ready needs more than kc.sh start-dev. The server must run in production mode (kc.sh start --optimized), behind nginx terminating TLS on a real Let’s Encrypt cert, with hostname set to the public HTTPS URL so the OIDC issuer baked into every token matches what relying parties verify against. PostgreSQL must be bound to 127.0.0.1 only. The master realm has to be hardened — admin password rotated, the default admin replaced by a named operator with MFA. proxy-headers=xforwarded and nginx need to agree on what X-Forwarded-Proto means, otherwise Keycloak emits issuer URLs and redirects with the wrong scheme. SSH needs password auth disabled while preserving root key access. None of these are individually critical — skip them and the IAM every other service trusts becomes the easiest hole in the network.

How to verify

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

ss -lntp | grep -E ':(80|443|8080|5432)\b'
# 127.0.0.1:5432  postgres
# 127.0.0.1:8080  keycloak
# 0.0.0.0:80      nginx
# 0.0.0.0:443     nginx

PostgreSQL on 5432 must be 127.0.0.1, never 0.0.0.0. The OIDC discovery endpoint for the master realm must return JSON with the public HTTPS issuer:

curl -fsS https://iam.example.com/realms/master/.well-known/openid-configuration | jq .issuer
# "https://iam.example.com/realms/master"

If issuer comes back as http://localhost:8080/... or http://iam.example.com/..., the hostname or forwarded-proto wiring is broken — every relying party will reject tokens.

The fix

Save the script below as /root/setup-keycloak-almalinux9.sh, then run it. It runs the installer flow on a fresh AlmaLinux 9.x VM: base update + EPEL, kernel tuning, file limits, firewalld with SSH + HTTP + HTTPS only, SSH hardening, dnf-automatic.timer for security updates, Temurin OpenJDK 21, PostgreSQL 15 bound to localhost, the official Keycloak tarball into /opt/keycloak, a kc-user service account, a keycloak.conf that includes proxy-headers=xforwarded and hostname, a built optimized server (kc.sh build), a systemd unit with LimitNOFILE=64000, nginx with the correct forwarded headers, Let’s Encrypt via certbot’s nginx plugin, and a poll loop that waits for :8080 and :443 before declaring success.

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

### AlmaLinux 9.x Keycloak clean VM installer
### Keeps root SSH key login enabled
### Disables SSH password login
### Enables automatic security updates
### Installs and configures PostgreSQL + Keycloak + nginx + Let's Encrypt
### No local backups; assumes VM-level backup
### Reboot remains manual

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

: "${KC_DOMAIN:?Set KC_DOMAIN=iam.example.com}"
: "${KC_EMAIL:?Set KC_EMAIL=ops@example.com for Let's Encrypt}"
KC_VERSION="${KC_VERSION:-26.0.5}"
KC_DB_PASSWORD="${KC_DB_PASSWORD:-$(openssl rand -hex 24)}"
KC_BOOTSTRAP_ADMIN_PASSWORD="${KC_BOOTSTRAP_ADMIN_PASSWORD:-$(openssl rand -hex 16)}"

echo
echo "========================================"
echo "Keycloak AlmaLinux 9.x Setup"
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 openssl

echo "==> Enabling time sync"
systemctl enable --now chronyd
timedatectl set-ntp true

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

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-keycloak.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

net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_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

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-keycloak.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

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 --reload

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 ChallengeResponseAuthentication 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 fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN

systemctl enable --now fail2ban

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

[emitters]
emit_via = stdio

[base]
debuglevel = 1
DNFAUTO

systemctl enable --now dnf-automatic.timer

echo "==> Installing Temurin OpenJDK 21"
cat > /etc/yum.repos.d/adoptium.repo <<'ADOPTIUM'
[Adoptium]
name=Adoptium
baseurl=https://packages.adoptium.net/artifactory/rpm/rhel/$releasever/$basearch
enabled=1
gpgcheck=1
gpgkey=https://packages.adoptium.net/artifactory/api/gpg/key/public
ADOPTIUM

dnf -y install temurin-21-jdk

echo "==> Installing PostgreSQL 15"
dnf -qy module disable postgresql || true
dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -y install postgresql15-server postgresql15

/usr/pgsql-15/bin/postgresql-15-setup initdb || true

echo "==> Locking PostgreSQL to localhost"
PG_DATA="/var/lib/pgsql/15/data"
PG_CONF="${PG_DATA}/postgresql.conf"
sed -i "s|^#*listen_addresses.*|listen_addresses = 'localhost'|" "$PG_CONF"

systemctl enable --now postgresql-15
systemctl restart postgresql-15

echo "==> Creating Keycloak database and role"
sudo -u postgres psql <<SQL
DO \$\$
BEGIN
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'kc_user') THEN
    CREATE ROLE kc_user LOGIN PASSWORD '${KC_DB_PASSWORD}';
  ELSE
    ALTER ROLE kc_user WITH PASSWORD '${KC_DB_PASSWORD}';
  END IF;
END
\$\$;
SQL

sudo -u postgres psql -tc "SELECT 1 FROM pg_database WHERE datname='keycloak'" | grep -q 1 \
  || sudo -u postgres createdb -O kc_user keycloak

echo "==> Creating kc-user service account"
if ! id -u kc-user >/dev/null 2>&1; then
  useradd --system --home-dir /opt/keycloak --shell /sbin/nologin kc-user
fi

echo "==> Installing Keycloak ${KC_VERSION}"
cd /opt
if [[ ! -d "/opt/keycloak-${KC_VERSION}" ]]; then
  wget -q "https://github.com/keycloak/keycloak/releases/download/${KC_VERSION}/keycloak-${KC_VERSION}.tar.gz"
  tar -xf "keycloak-${KC_VERSION}.tar.gz"
  rm -f "keycloak-${KC_VERSION}.tar.gz"
fi

ln -sfn "/opt/keycloak-${KC_VERSION}" /opt/keycloak

echo "==> Writing Keycloak configuration"
cat > /opt/keycloak/conf/keycloak.conf <<KCCONF
db=postgres
db-username=kc_user
db-password=${KC_DB_PASSWORD}
db-url=jdbc:postgresql://127.0.0.1:5432/keycloak
db-pool-initial-size=5
db-pool-min-size=5
db-pool-max-size=20

http-enabled=true
http-host=127.0.0.1
http-port=8080
proxy-headers=xforwarded
hostname=https://${KC_DOMAIN}
hostname-strict=true

log=console,file
log-file=/var/log/keycloak/keycloak.log
log-level=info
KCCONF

mkdir -p /var/log/keycloak
chown -R kc-user:kc-user /opt/keycloak /opt/keycloak-${KC_VERSION} /var/log/keycloak

echo "==> Building optimized server"
sudo -u kc-user /opt/keycloak/bin/kc.sh build

echo "==> Writing systemd unit"
cat > /etc/systemd/system/keycloak.service <<'UNIT'
[Unit]
Description=Keycloak
After=network.target postgresql-15.service
Requires=postgresql-15.service

[Service]
Type=simple
User=kc-user
Group=kc-user
Environment=KC_BOOTSTRAP_ADMIN_USERNAME=admin
EnvironmentFile=/etc/keycloak/admin.env
ExecStart=/opt/keycloak/bin/kc.sh start --optimized
WorkingDirectory=/opt/keycloak
LimitNOFILE=64000
Restart=on-failure
RestartSec=10
SuccessExitStatus=0 143

[Install]
WantedBy=multi-user.target
UNIT

mkdir -p /etc/keycloak
cat > /etc/keycloak/admin.env <<ADMINENV
KC_BOOTSTRAP_ADMIN_PASSWORD=${KC_BOOTSTRAP_ADMIN_PASSWORD}
ADMINENV
chmod 600 /etc/keycloak/admin.env
chown root:root /etc/keycloak/admin.env

systemctl daemon-reload
systemctl enable --now keycloak

echo "==> Waiting for Keycloak on 127.0.0.1:8080"
for i in {1..120}; do
  if ss -lntp | grep -q '127.0.0.1:8080'; then
    break
  fi
  sleep 2
done

if ! ss -lntp | grep -q '127.0.0.1:8080'; then
  echo "Keycloak failed to listen on 127.0.0.1:8080"
  journalctl -u keycloak -n 200 --no-pager || true
  exit 1
fi

echo "==> Installing nginx and certbot"
dnf -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/conf.d/keycloak.conf <<NGINX
upstream keycloak_backend {
    server 127.0.0.1:8080;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${KC_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${KC_DOMAIN};

    client_max_body_size 20M;
    proxy_read_timeout   300s;
    proxy_send_timeout   300s;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    location / {
        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_set_header X-Forwarded-Host \$host;
        proxy_set_header X-Forwarded-Port 443;
        proxy_http_version 1.1;
        proxy_pass http://keycloak_backend;
    }
}
NGINX

rm -f /etc/nginx/conf.d/default.conf

nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${KC_EMAIL}" -d "${KC_DOMAIN}" --redirect

systemctl enable --now certbot.timer

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

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

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Kernel:"
uname -r

echo
echo "SELinux:"
getenforce || true

echo
echo "SSH effective settings:"
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication) ' || true

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|5432|8080)\b' || true

echo
echo "Services:"
systemctl is-active postgresql-15 keycloak nginx fail2ban chronyd || true

echo
echo "OIDC discovery (must return JSON with the HTTPS issuer):"
curl -fsS "https://${KC_DOMAIN}/realms/master/.well-known/openid-configuration" | jq -r .issuer || true

echo
echo "Bootstrap admin: admin / ${KC_BOOTSTRAP_ADMIN_PASSWORD}"
echo "DB password: ${KC_DB_PASSWORD}"
echo "(Both written above. Record them in your secrets manager now.)"

echo
echo "Web UI:"
echo "https://${KC_DOMAIN}/admin/"

echo
echo "Final step:"
echo "Sign in as admin, create a named operator account in the master realm, grant it realm-admin, sign out, sign back in as the named account, then disable the bootstrap admin user."

Make it executable and run it:

chmod 700 /root/setup-keycloak-almalinux9.sh
KC_DOMAIN=iam.example.com KC_EMAIL=ops@example.com /root/setup-keycloak-almalinux9.sh

The bootstrap admin password is printed at the end — record it in your secrets manager, then log in to https://iam.example.com/admin/, create a named human admin in the master realm, grant it realm-admin, sign back in as that account, and disable the bootstrap admin user. Enable OTP as a required action on the master realm. Host-level backups are not configured here; pg_dump of the keycloak database should be covered by your VM snapshot policy.

When IAM behaviour has to stay consistent across realm changes, theme upgrades and quarterly Keycloak releases, that’s part of Monitoring and on-call support — or book a quick infrastructure review.