Context & Why It Matters
The clock strikes 2:15 AM. PagerDuty alerts start blaring incessantly: users cannot complete payments on the mobile app. Simultaneously, the internal CRM dashboard reports a flood of token authentication failures. The root cause? The company was maintaining four isolated user account databases across four server clusters. When the primary authentication cluster encountered a bottleneck and became overloaded, the background sync mechanism collapsed with it, paralyzing the entire sales platform for nearly two hours.
Relying on custom-built authentication modules and fragmented users tables poses severe operational risks once traffic scales to tens of thousands of daily active users. At this point, migrating to a standardized Identity and Access Management (IAM) solution like Keycloak on Ubuntu 24.04 LTS provides the most robust, sustainable long-term foundation.
Keycloak handles Single Sign-On (SSO), Identity Brokering, and Social Login out of the box via OpenID Connect (OIDC) or SAML 2.0. All tasks—from issuing JSON Web Tokens (JWT) to session revocation—are centralized. Satellite applications no longer need to store user credentials directly; instead, they simply redirect users to Keycloak to retrieve tokens.
Installation
In a production environment, you should never use the default in-memory H2 database. Instead, we will deploy Quarkus-powered Keycloak paired with PostgreSQL 16 and OpenJDK 21 directly on an Ubuntu 24.04 server.
1. Update the System and Install OpenJDK 21
Modern versions of Keycloak require Java 21 LTS to optimize memory management and thread handling:
sudo apt update && sudo apt upgrade -y
sudo apt install -y openjdk-21-jdk-headless curl tar jq
java -version
2. Install and Prepare PostgreSQL 16
Install the PostgreSQL server from the official Ubuntu repositories:
sudo apt install -y postgresql postgresql-contrib
sudo systemctl enable postgresql --now
Create the database and grant full ownership to the Keycloak user:
sudo -u postgres psql <<EOF
CREATE DATABASE keycloak_db WITH ENCODING 'UTF8';
CREATE USER keycloak_user WITH ENCRYPTED PASSWORD 'UltraSecurePassword2026!@#';
ALTER DATABASE keycloak_db OWNER TO keycloak_user;
\c keycloak_db
GRANT ALL ON SCHEMA public TO keycloak_user;
\q
EOF
3. Create a System User and Download Keycloak
To adhere to the principle of least privilege, never run network services as root. Create a dedicated system user instead:
sudo groupadd -r keycloak
sudo useradd -r -g keycloak -d /opt/keycloak -s /usr/sbin/nologin keycloak
Fetch the latest stable release directly via the GitHub API and extract it into the /opt/keycloak directory:
KC_VERSION=$(curl -s https://api.github.com/repos/keycloak/keycloak/releases/latest | jq -r .tag_name)
wget https://github.com/keycloak/keycloak/releases/download/${KC_VERSION}/keycloak-${KC_VERSION}.tar.gz -O /tmp/keycloak.tar.gz
sudo tar -xzf /tmp/keycloak.tar.gz -C /opt/
sudo rm -rf /opt/keycloak
sudo mv /opt/keycloak-${KC_VERSION} /opt/keycloak
sudo chown -R keycloak:keycloak /opt/keycloak
Detailed Configuration
Keycloak’s Quarkus architecture requires you to define options in the keycloak.conf file and run an explicit build step before launching the application.
1. Configure the Database and Reverse Proxy
Open the primary configuration file located at /opt/keycloak/conf/keycloak.conf:
sudo nano /opt/keycloak/conf/keycloak.conf
Specify the database connection details and configure secure proxying behind Nginx:
# PostgreSQL Database Configuration
db=postgres
db-username=keycloak_user
db-password=UltraSecurePassword2026!@#
db-url=jdbc:postgresql://127.0.0.1:5432/keycloak_db
# HTTP & Reverse Proxy Configuration
http-enabled=true
http-host=127.0.0.1
http-port=8080
proxy-headers=xforwarded
# Official Hostname (prevents Host Header Poisoning attacks)
hostname=auth.itfromzero.local
# Enable health check endpoints and monitoring metrics
health-enabled=true
metrics-enabled=true
2. Build the Optimized Application
The build command allows Quarkus to pre-load database drivers and compile configurations, slashing startup times from 20 seconds down to roughly 3–5 seconds:
sudo -u keycloak /opt/keycloak/bin/kc.sh build
Once the message Server configuration updated and persisted. Optimized build completed appears on the screen, the packaging process is complete.
3. Initialize the Admin Account
Pass administrative credentials via environment variables on the initial run so Keycloak can provision the admin user:
export KEYCLOAK_ADMIN="admin_sec"
export KEYCLOAK_ADMIN_PASSWORD="SuperStrongAdminPassword2026!"
sudo -E -u keycloak /opt/keycloak/bin/kc.sh start --optimized
Once the logs show that the server is listening on port 8080, press Ctrl + C to stop the process. The administrative credentials have now been hashed and safely persisted in PostgreSQL tables.
4. Set Up the Systemd Service
Create a systemd unit file so Ubuntu can automatically manage the lifecycle and restart Keycloak upon unexpected failures:
sudo nano /etc/systemd/system/keycloak.service
Add the following configuration to the file:
[Unit]
Description=Keycloak Identity and Access Management Server
After=network.target postgresql.service
Wants=postgresql.service
[Service]
Type=exec
User=keycloak
Group=keycloak
Environment="JAVA_OPTS_APPEND=-Xms1024m -Xmx2048m -XX:+UseG1GC"
ExecStart=/opt/keycloak/bin/kc.sh start --optimized
TimeoutStartSec=600
TimeoutStopSec=60
Restart=on-failure
RestartSec=10
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
Reload the systemd configuration and enable the service to start immediately:
sudo systemctl daemon-reload
sudo systemctl enable --now keycloak
Testing & Operational Monitoring
Proactive monitoring ensures you resolve potential issues before users have a chance to file support tickets.
1. Check Process Status and Logs
Verify that the service is running and tail the startup logs in real time:
sudo systemctl status keycloak
sudo journalctl -u keycloak -f -o cat
The service is ready to accept incoming requests once you see the message:
Listening on: http://127.0.0.1:8080. Started Keycloak in ...ms
2. Inspect Health Endpoints
Keycloak provides built-in standard liveness and readiness probes:
curl -i http://127.0.0.1:8080/health/live
curl -i http://127.0.0.1:8080/health/ready
If PostgreSQL loses its connection or connection pool exhaustion occurs, the /health/ready endpoint returns an HTTP 503 status code with detailed diagnostics. You can integrate this probe into Prometheus or a load balancer to automatically isolate failing nodes.
3. Troubleshooting Common Issues
- Error KC-SERVICES0001 (Failed to connect to database): Check
/etc/postgresql/16/main/pg_hba.confto ensure local md5/scram-sha-256 connections are permitted. Runss -tlpn | grep 5432to verify that PostgreSQL is actively listening on its port. - Process Terminated by Linux OOM Killer: Run
dmesg -T | grep -i oomto investigate. By default, the JVM may exceed memory limits unless heap size is constrained. Tune the-Xmxparameter in the service file to keep memory consumption below 75% of total VPS RAM. - Infinite Redirect Loop: Often happens when Nginx terminates SSL but forwards plain HTTP requests to Keycloak without the original protocol header. Ensure your Nginx configuration contains the
proxy_set_header X-Forwarded-Proto https;directive and Keycloak has theproxy-headers=xforwardedsetting enabled.
You can now navigate to https://auth.itfromzero.local/admin to create a new Realm, configure Client IDs for downstream applications, and enforce multi-factor authentication (MFA/2FA) across your organization.
