Docker images often are parameterized through startup arguments or environment variables. There are often situations however, where certain aspects cannot be configured this way. Instead, you either have to create images for all possible configurations, or implement an extended configuration strategy.
In this article we show how to parameterize a KeyCloak container with dynamic redirect URIs at startup. The general approach may be used for other applications as well.
KeyCloak
A KeyCloak realm needs to be configured with valid “redirect URIs”, i.e. a list of plain URIs or patterns the browser may be redirected to after successful login. In a containerized environment these URIs usually cannot be configured statically, if you do not want to restrict the application to hard-coded patterns.
Startup
What we do is to extend the standard startup process by adding our own entrypoint.sh
script in the Dockerfile
:
FROM quay.io/keycloak/keycloak:24.0.4
...
VOLUME /opt/keycloak/startup-scripts
ENTRYPOINT ["/opt/keycloak/bin/entrypoint.sh"]
This script mainly contains code to start the dynamic configuration in background (and give KeyCloak some time to startup itself):
#!/usr/bin/env bash
(sleep 10 ; /opt/keycloak/bin/startup_scripts.sh) &
exec /opt/keycloak/bin/kc.sh "$@"
Waiting
What startup_scripts.sh
does, is to look into a given folder (which should be mounted as a volume on the host) for custom scripts to be executed. First, we have to wait however until KeyCloak has finished its own startup process. There are several ways to accomplish that, you may for example use some variant of the wait-for-it script in order to wait for the server.
We simply try to login to KC’s admin console and wait for this command to succeed.
waitForKeyCloak() {
local start="Failed"
while [[ $start =~ "Failed" || $start =~ "null" || $start =~ "404" || $start =~ "Invalid" ]]; do
./kcadm.sh config credentials --server "http://localhost:8080/auth" --realm master --user admin --password 'secret!' &> /tmp/start
start=$(</tmp/start)
sleep 5
done
}
Configure redirect URIs
Finally, we run our script (placed in the mounted volume) that configures KeyCloak using an environment variable defined at startup, e.g. in a docker-compose.yml
file.
#!/bin/bash
redirectUris="[\"https://localhost:11143/*\", \"https://${HOST_HOSTNAME,,}:11143/*\"]"
echo "******************* Configure Redirect URIs ${redirectUris} *******************"
./kcadm.sh update -r myrealm clients/myclient -s rootUrl="https:///${HOST_HOSTNAME,,}:14043"
./kcadm.sh update -r myrealm clients/myclient -s adminUrl="https:///${HOST_HOSTNAME,,}/auth/admin"
./kcadm.sh update clients/myclient -r myrealm -s redirectUris="$redirectUris"
echo "******************* Redirect URIs configured *******************"