External Postgres Database

I would like to use an external PG database. I have an application database (app_db) which is already running. Can I create a new DB (kc_db) in the same PG instance? How do I create required database schema for Keycloak? Does it run SQL scripts on startup? OR my app_db has user & roles tables. Can I use it for Keycloak? Btw, we don’t have a need to run in a cluster.


In a PG instance you can create as many schema’s as you like. For more information on how to create a new schema take a look at https://www.postgresql.org/docs/12/sql-createschema.html or https://www.keycloak.org/docs/latest/server_installation/#postgresql-database

Keycloak can be configured with a lot of db’s and options, take a look at https://www.keycloak.org/docs/latest/server_installation/#_database on how to do this.
Keycloak uses Liquibase for managing database migrations and will initialize all tables on startup when nothing is there.

On the matter of your existing db with user & roles, no, you can’t use this for Keycloak. Depending on your needs however you can combine both, but again this depends on you tech stack and setup.

Let me give you an example on how you can approach things or how I do things in one of my projects.
Keycloak has it’s database and my app has it’s own database(s). I keep these completely separate as this makes it easier to migrate to newer versions of Keycloak.
My app db has it’s own user table with the UUID that Keycloak created for each user. This makes it easy to resolve the user in my own app when I receive the JWT because I know the UUID in the token and can create the principal based on that.
If you want to keep your users and roles in your own db you can perfectly do that. For migrating existing users to Keycloak you can for example create a Keycloak user through the Keycloak REST API and send the user a reset account email or something like that. Or create your own email with a reset link and tell them of this migration. It all depends on your needs.

Don’t forget to have fun.

1 Like

Thanks. I just configured the keycloakDS in the xml…all set!