Running Keycloak with Docker

Keycloak’s latest Docker image is available on the quay.io Docker repository. Let’s see in this tutorial how we can boot it with Docker, using some common environment parameters.

So as said, you can grab the latest Docker image of Keycloak with:

$ docker pull quay.io/keycloak/keycloak

On the other hand, when it’s time to run it, you would typically use some environment variables to make it fit for your applications. Let’s see some use cases.

Starting Keycloak and adding an Admin User

That is the most obvious use case, as an Admin user is needed in order to manage Keycloak:

docker run --rm --name keycloak -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin  -p 8180:8180  -it quay.io/keycloak/keycloak  -b 0.0.0.0  -Djboss.http.port=8180

Additionally, please note that we have bound Keycloak to a different port from the default one (8080) in case you are already using that port for other services.

You can also add an Admin user on an already running container by executing:

docker exec <CONTAINER> /opt/jboss/keycloak/bin/add-user-keycloak.sh -u <USERNAME> -p <PASSWORD>

Then restart the container with:

docker restart <CONTAINER>

Importing a Keycloak Realm at start up

Just in case you want to boot Keycloak and have your Realm imported, you can add the KEYCLOAK_IMPORT Environment variable and the Volume argument (-v) to specify the path where the JSON Realm file will be picked up:

docker run --rm \ 
--name keycloak \ 
-e KEYCLOAK_USER=admin \ 
-e KEYCLOAK_PASSWORD=admin \ 
-e KEYCLOAK_IMPORT=/tmp/realm.json -v /tmp/realm.json:/tmp/realm.json \ 
-p 8180:8180 \ 
-it quay.io/keycloak/keycloak \ 
-b 0.0.0.0 \ 
-Djboss.http.port=8180 \ 
-Dkeycloak.profile.feature.upload_scripts=enabled

Exporting a Keycloak Realm

If you want to export a realm that you have created you’ll need to ensure the container running Keycloak has a volume mapped. For example you can start Keycloak setting the volume (‘v’) option to the /tmp folder:

docker run -d -p 8180:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -v $(pwd):/tmp --name keycloak quay.io/keycloak/keycloak

Then, you can then get the export from this instance by running:

docker exec -it keycloak keycloak/bin/standalone.sh \ 
-Djboss.socket.binding.port-offset=100 -Dkeycloak.migration.action=export \ 
-Dkeycloak.migration.provider=singleFile \ 
-Dkeycloak.migration.realmName=my_realm \ 
-Dkeycloak.migration.usersExportStrategy=REALM_FILE \ 
-Dkeycloak.migration.file=/tmp/my_realm.json

(notice we use -Djboss.socket.binding.port-offset=100 so that the export runs on a different port than Keycloak itself).

If you want to learn how to replace the Keycloak’s default H2 Database, please check this tutorial: Configuring Keycloak Database