Import a realm when running with Docker?

I am looking to set up Keycloak through Docker as one of many services in a monorepo.

It looks like in previous versions it was possible to import a realm when Keycloak boots up but from what I can see in this Github issue that’s no longer supported.

Here is what I’m trying to achieve:

  • When developing locally I want to be able to spin up a container where Keycloak has an identical configuration to production.
  • When I deploy to production for the first time I want to be able to set up a realm programatically.
  • On subsequent deploys it would ignore the import (as it’s already been done) but ideally it would be possible to apply a migration if there’s a need for any changes.

Here’s the relevant section from my docker-compose.yml

  auth:
    build:
      context: auth
    depends_on:
      db-auth:
        condition: service_started
      nginx-proxy:
        condition: service_started
    ports:
      - "3001:8080"
    environment:
      KC_DB_ADDR: db-auth
      KC_DB_USERNAME: "postgres"
      KC_DB_PASSWORD: ${POSTGRES_PASSWORD}
      KC_HOSTNAME: auth.app.local
      KEYCLOAK_ADMIN: admin
      KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD}
      KEYCLOAK_IMPORT: /opt/keycloak/imports/test-realm.json -Dkeycloak.profile.feature.upload_scripts=enabled
    restart: always
    command: start # for prod it also needs "--server-config=standalone-ha.xml"
    volumes:
      - "./auth/config:/opt/keycloak/imports"
    networks:
      - app-network

My Dockerfile is setup like this:

FROM quay.io/keycloak/keycloak:latest AS builder

# Various bits of config

RUN /opt/keycloak/bin/kc.sh build

FROM quay.io/keycloak/keycloak:latest
COPY --from=builder /opt/keycloak/ /opt/keycloak/

# ... More config

ENTRYPOINT ["/opt/keycloak/bin/kc.sh"]

Nothing I tried worked to run my import file. That’s when I discovered that Github issue above.

If anyone can provide some advice it would be much appreciated.

Importing a realm during startup:

Thank you! That’s turned out to be quite simple.

Are there any guides available for doing migrations?