Skip to content

Instantly share code, notes, and snippets.

@sarath-soman
Last active May 2, 2025 15:44
Show Gist options
  • Save sarath-soman/5d9aec06953bbd0990c648605d4dba07 to your computer and use it in GitHub Desktop.
Save sarath-soman/5d9aec06953bbd0990c648605d4dba07 to your computer and use it in GitHub Desktop.
Keycloak docker compose with health checks
# Keycloak containers doesn't come with curl or wget in it, this forces the users to use alternative mechanisms to realise
# health check for the keycloak standard containers. This example leverages the capability of modern Java to dynamically
# compile a *.java source file and execute it on the fly using the `java` command. The HealthCheck class uses
# java.net.URL to open a connection to the `health/live` endpoint of keycloak and exits the process with a non-zero status
# if the http status is not `Ok`
version: '3'
services:
############################
# Keycloak service
############################
keycloak:
image: quay.io/keycloak/keycloak:22.0.5
command:
- start-dev
- --import-realm
environment:
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
DB_VENDOR: h2
KC_HEALTH_ENABLED: true
ports:
- '8080:8080'
volumes:
- ./keycloak:/opt/keycloak/data/import
healthcheck:
test: ['CMD-SHELL', '[ -f /tmp/HealthCheck.java ] || echo "public class HealthCheck { public static void main(String[] args) throws java.lang.Throwable { System.exit(java.net.HttpURLConnection.HTTP_OK == ((java.net.HttpURLConnection)new java.net.URL(args[0]).openConnection()).getResponseCode() ? 0 : 1); } }" > /tmp/HealthCheck.java && java /tmp/HealthCheck.java http://localhost:8080/health/live']
interval: 5s
timeout: 5s
retries: 30
@codespearhead
Copy link

For what it’s worth, I’ve updated my previous answer [1] to bump the Keycloak version to v26.1.0-0 (released on 2025-01-15), and I confirm that no changes to the health check logic were necessary.

[1] https://gist.github.com/sarath-soman/5d9aec06953bbd0990c648605d4dba07?permalink_comment_id=5376088#gistcomment-5376088

@AlecKotovichSAM
Copy link

To avoid Java warning [deprecation] URL(String) in URL has been deprecated, I rewrote it like that:

    healthcheck:
      test: ['CMD-SHELL', '[ -f /tmp/HealthCheck.java ] || echo "public class HealthCheck { public static void main(String[] args) throws java.lang.Throwable { java.net.URI uri = java.net.URI.create(args[0]); System.exit(java.net.HttpURLConnection.HTTP_OK == ((java.net.HttpURLConnection)uri.toURL().openConnection()).getResponseCode() ? 0 : 1); } }" > /tmp/HealthCheck.java && java /tmp/HealthCheck.java http://localhost:9000/health/live']
      interval: 5s
      timeout: 5s
      retries: 5

Worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment