Step-by-Step Tutorial: Setting Up Keycloak with PostgreSQL on Ubuntu 22.04
Tags: keycloak, sso
Published: 2023-12-28 06:38:44

**This guide provides step-by-step instructions on installing Keycloak with PostgreSQL on Ubuntu 22.04.**

## Step 1: Update System Packages
```bash
sudo apt update
sudo apt upgrade -y
```
## Step 2: Install PostgreSQL
```bash
sudo apt install postgresql postgresql-contrib -y
```
## Step 3: Create a PostgreSQL Database and User
```bash
sudo su - postgres
# Creating a New Role
createuser --interactive --pwprompt keycloak
# Creating a New Database
createdb keycloakdb
# Accessing the keycloak Database using keycloak user
psql -d keycloak -U keycloak -W -h localhost
\q
exit  
```
## Step 4: Install OpenJDK
```bash
sudo apt install openjdk-17-jre-headless openjdk-17-jdk-headless -y
```
## Step 5: Download and Install Keycloak
```bash
sudo apt install software-properties-common ca-certificates chrony wget net-tools -y
wget https://github.com/keycloak/keycloak/releases/download/23.0.0/keycloak-23.0.0.tar.gz
tar zxvf keycloak-23.0.0.tar.gz
sudo mv keycloak-23.0.0 /opt/keycloak
```
## Step 6: Configure Keycloak
Open the Keycloak configuration file for editing:
```bash
sudo nano /opt/keycloak/conf/keycloak.conf

# Keycloak Database Configuration
db=postgres
db-username=<db_username>
db-password=<db_password>
db-url=jdbc:postgresql://<db_host>/<db_name>

# Health and Metrics Configuration
health-enabled=true
metrics-enabled=true

# HTTPS Configuration
https-certificate-file=/opt/keycloak/conf/keycloak-server.crt.pem
https-certificate-key-file=/opt/keycloak/conf/keycloak-server.key.pem
https-port=443

# Hostname Configuration
hostname=<Keycloak Domain Name>  #Example :keycloak.example.com

```
## Step 7: Generate Self-Signed SSL Certificate (For Development/Local Environment)
If you are running Keycloak for development or local environments, you can use a self-signed SSL certificate. Run the following command to generate one:
```bash
sudo openssl req -newkey rsa:2048 -nodes \
  -keyout /opt/keycloak/conf/keycloak-server.key.pem -x509 -days 3650 -out /opt/keycloak/conf/keycloak-server.crt.pem
```
This command generates a self-signed SSL certificate valid for 10 years. Adjust the duration as needed.

The SSL certificate files (**keycloak-server.crt.pem and keycloak-server.key.pem**) will be saved in the **/opt/keycloak/conf/** directory.

## Step 8: Export Initial Admin Username and Password
After Keycloak is set up, it's useful to export the initial admin username and password for future reference or automation. In this step, we'll export these values and set them in the system environment.
```bash
# Export initial admin username and password
echo "KEYCLOAK_ADMIN=admin" | sudo tee -a /etc/environment
echo "KEYCLOAK_ADMIN_PASSWORD=admin" | sudo tee -a /etc/environment
```
By adding these entries to /etc/environment, you make these variables available system-wide, ensuring Keycloak and other processes can access them.
```bash
# Source the environment file to apply changes
source /etc/environment
```
Sourcing the environment file ensures that the changes take effect without the need to reboot.
## Step 9: Build Keycloak
Building Keycloak involves preparing it for execution and resolving any dependencies. Navigate to the Keycloak bin directory and execute the build command:

```bash
# Navigate to the Keycloak bin directory
cd /opt/keycloak/bin

# Execute the build command
./kc.sh --verbose build
```
This command initiates the build process, and the --verbose flag provides more detailed output, helping you monitor the build progress.

## Step 10: Create Systemd Unit File

To manage Keycloak as a systemd service, create a systemd unit file. This file defines how the service should start, stop, and behave in various situations.

Create the systemd unit file with the following content:

```bash

[Unit]
Description=Keycloak Identity Provider
Requires=network.target
After=syslog.target network.target

[Service]
Type=idle
User=root
Group=root
#RemainAfterExit=yes
LimitNOFILE=102642
ExecStart=/opt/keycloak/bin/kc.sh start --log=console,file
ExecStop=/opt/keycloak/bin/kc.sh stop 
WorkingDirectory=/opt/keycloak
StandardOutput=null

[Install]
WantedBy=multi-user.target
```
This unit file specifies that Keycloak requires the network, runs as the root user, and defines the start command and working directory. The LimitNOFILE setting increases the maximum number of open file descriptors.

After creating the unit file, reload systemd, enable the service, start it, and check its status:

```bash
# Reload systemd to apply changes
sudo systemctl daemon-reload

# Enable the Keycloak service to start on boot
sudo systemctl enable keycloak.service

# Start the Keycloak service
sudo systemctl start keycloak.service

# Check the status of the Keycloak service
sudo systemctl status keycloak.service
```
These commands ensure that Keycloak is set up to run as a systemd service, starts automatically on boot, and can be monitored using systemctl.

Adjust configurations and paths as needed based on your environment and preferences.


## Step 11: Access Keycloak Admin Console

1. Open your web browser and navigate to the Keycloak admin console using the URL: https://localhost/admin/master/console/
If you configured a custom hostname in `Step 6`, replace `localhost` with the configured hostname.

2. You will be presented with the Keycloak login page. Enter the admin username and password that you exported in `Step 8`.
**Username: `admin`**
**Password: `admin`**

3. After successful login, you'll have access to the Keycloak admin console. Here, you can configure realms, clients, users, and various authentication settings.
   Remember to keep your admin credentials secure, especially in a production environment. If you plan to use Keycloak in a production setting, consider configuring SSL/TLS and securing access to the admin console accordingly.
  Explore the admin console to set up realms, clients, and other configurations based on your application's requirements.