How to Use Keycloak with MySQL Database (Quarkus)

The new version of Keycloak comes with its own embedded dev-file database to persist data. This default database is designed to run instantly and so is suitable only for use in a test environment. In a production environment, more mature relational database must be used.

In this tutorial, you will learn how to configure Keycloak (powered by Quarkus) to use with MySQL database instead of its default dev-file database.

What You Need

Here's how you can set up Keycloak with MySQL:

  1. Create a MySQL database: You need to have MySQL installed on your system or available in your network. Make sure you have the necessary permissions to create a database and user. Log in to your MySQL server and create a new database that Keycloak will use to store its data.
  2. Execute the following MySQL commands sequentially:

    CREATE DATABASE keycloak;
    CREATE USER 'keycloak'@'localhost' IDENTIFIED BY 'MyPassword$';
    GRANT ALL PRIVILEGES ON keycloak.* TO 'keycloak'@'localhost';

    Here, the first command will create a new database called 'keycloak'.

    The second command will create a new user named 'keycloak'. It's a good practice to create a dedicated MySQL user for Keycloak with the appropriate permissions on the database.

    The third command will grant all privileges to the user 'keycloak'.

  3. Configure Keycloak to use MySQL Database: Go to the "conf" directory of the Keycloak Server. Open the "keycloak.conf" file with a text editor, such as Notepad. Uncomment and update the following properties in the conf/keycloak.conf file:

  4. db=mysql
    
    db-username=keycloak
    
    db-password=MyPassword$
    
    #db-url=protocol//[host][/database]
    db-url=jdbc:mysql://localhost:3306/keycloak

    To uncomment a line in the keycloak.conf file, you simply need to remove the # symbol from the beginning of the line. When you remove the #, the line becomes an active configuration setting that will be read and interpreted by the application.

  5. Next, open a command prompt/terminal and navigate to the 'bin' directory of the Keycloak Server:

  6. cd keycloak-12.0.1/bin/
  7. Run the Keycloak Server:

  8. For Windows

    .\kc.bat start-dev

    For Linux/Ubuntu

    ./kc.sh start-dev

    If configured correctly, Keycloak server should start without any errors.

  9. Go to your browser and open http://localhost:8080. You will see the Keycloak Admin Console.
  10. Learn more here.