Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring dockerized Keycloak by CLI commands

I'm trying to configure a dockerized Keycloak server like creating a realm from CLI command in the Dockerfile:

FROM quay.io/keycloak/keycloak:11.0.0

# Create realm "realm_borrar" on keycloak
RUN /opt/jboss/keycloak/bin/kcadm.sh create realms -s realm=my_new_realm -s enabled=true -o --server http://localhost:8080/auth --realm master --user admin --password admin

The result of docker build -f ... is:

Logging into http://localhost:8080/auth as user admin of realm master
Failed to send request - Connect to localhost:8080 [localhost/127.0.0.1] failed: Connection refused (Connection refused)

If I run the container (created with the same Dockerfile but removing the RUN sentence) and I execute the same CLI command (kcadm.sh ....) it works.

What should be the proper way to config Keycloak in the Dockerfile?

Thanks.

like image 532
Paco Abato Avatar asked Oct 21 '20 10:10

Paco Abato


2 Answers

Here is an example on how to do it for ubuntu...

  1. At a terminal, run Keycloak as a dockerfile, e.g.:

    docker run --name keycloak -p 8484:8080 -e DB_VENDOR=h2 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin jboss/keycloak:11.0.0 
    
  2. At another terminal, run the CLI commands you need as exec commands for the container, e.g. for kcadm.sh get realms do:

    docker exec -it keycloak /opt/jboss/keycloak/bin/kcadm.sh get realms --server http://localhost:8080/auth --realm master --user admin --password admin 
    

If you want to run everything on the same terminal, use -d (detach) on the first docker command.

For create realms using a file, map the directory of the file inside keycloack when running (mapping files directly should also work in theory) e.g.:

    docker run --name keycloak -p 8484:8080 -d -e DB_VENDOR=h2 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -v host_abs_path:/cfg jboss/keycloak:11.0.0 
    #wait for keycloak to start...
    sleep 10
    docker exec -it keycloak /opt/jboss/keycloak/bin/kcadm.sh create realms --server http://localhost:8080/auth --realm master --user admin --password admin -f /cfg/my_realms.json
like image 128
ntg Avatar answered Sep 25 '22 14:09

ntg


Obviously, Keycloak must be running and it must be connected to the DB, when you want to add realm. And that's not a case when you are building Docker image. It can be done only when container is running, so use startup scripts.

https://hub.docker.com/r/jboss/keycloak/

A custom script can be added by creating your own Dockerfile:

FROM keycloak COPY custom-scripts/ /opt/jboss/startup-scripts/

like image 21
Jan Garaj Avatar answered Sep 26 '22 14:09

Jan Garaj