Umberto D'Ovidio

Keycloak Local Development Config

Recently I found myself setting up a local development environment where Keycloak is used. I’ve created a repo that can be used as a reference when needed in the future.

Keycloak offers a docker container with several configuration options. I decided to run Keycloak with Postgres. Here’s my docker-compose file

 1version: "3.8"
 2services:
 3  db:
 4    image: postgres:12
 5    restart: always 
 6    ports:
 7      - 5432:5432
 8    volumes:
 9      - /c/db:/var/lib/postgresql/data
10      # This will bind the files inside the pgscripts to docker-entrypoint-initdb.d
11      # The scripts will be run on startup
12      - $PWD/postgres:/docker-entrypoint-initdb.d
13    env_file:
14      - .env.dev
15  wait-for-db:
16    image: dadarek/wait-for-dependencies
17    depends_on:
18      - db 
19    command: db:5432
20  keycloak:
21    image: jboss/keycloak
22    ports:
23      - 8080:8080
24    env_file:
25      - .env.dev

To make things more interesting, I’ve added a boostrap script for Postgres that creates a separate database dedicated to Keycloak, which allows for a nice separation in case later on we want to reuse the same Postgres instance for some other application.

1#!bin/sh
2psql << EOF 
3CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';
4CREATE DATABASE $DB_DATABASE OWNER $DB_USER;
5EOF

Note that the bootstrap script is using the here document in order to access environment variables with sql statements. A neat trick!

Another interesting thing is that all the environment variables configuration is done in a separate env file, keeping our docker-compose file cleaner. To run the app, the docker-compose file I’ve created a two liner script

1docker-compose run --rm  wait-for-db
2docker-compose up -d keycloak 

This first run wait-for-db. Once that command exit, we are sure that Postgres is ready to accept connections, so we can then launch Keycloak. If we wouldn’t do this, Keycloak would fail on startup since it cannot connect to Posgres.