bolt Valebyte VPS from $4/mo — NVMe, 60s deploy.

Get a VPS arrow_forward

Keycloak on VPS: installation, configuration, and maintenance

calendar_month June 11, 2026 schedule 23 min read visibility 33 views
person
Valebyte Team
Keycloak on VPS: installation, configuration, and maintenance

Keycloak on a VPS is an effective way to deploy a powerful Identity and Access Management (IAM) system for your applications, providing centralized authentication and authorization with full control over data and infrastructure.

What is Keycloak and why deploy it on a VPS?

Keycloak is an open-source Identity and Access Management (IAM) solution developed by Red Hat. It provides a wide range of features for secure user authentication and authorization in web applications, mobile applications, and RESTful services. With Keycloak, you can easily add Single Sign-On (SSO), federated authentication, support for OpenID Connect, OAuth 2.0, and SAML 2.0 standards, as well as user and role management.

Deploying Keycloak on a VPS is an optimal solution for many companies and developers who need full control over their IAM solution without expensive cloud subscriptions or the limitations of SaaS services. This allows for flexible configuration, scalability, and security tailored to the specific needs of your project or business. You become the full owner of your data and are not dependent on third-party providers, which is critically important for compliance and privacy.

Keycloak Features: From SSO to MFA

Keycloak doesn't just provide basic authentication; it's a comprehensive platform with many advanced features:

  • Single Sign-On (SSO): Users only need to log in once to access all connected applications. This significantly improves user experience and reduces support load.
  • Standards Support: Full compatibility with OpenID Connect, OAuth 2.0, and SAML 2.0 makes Keycloak a universal solution that easily integrates with most modern applications and services.
  • Multi-Factor Authentication (MFA): Built-in support for various MFA methods, such as OTP (one-time passwords) via Google Authenticator or FreeOTP, enhances security.
  • User and Role Management: A user-friendly administrative interface allows you to create and manage users, groups, roles, and permissions.
  • Social Login: The ability to integrate with popular providers like Google, Facebook, GitHub simplifies the registration and login process for users.
  • Federated Authentication: Support for LDAP and Active Directory to synchronize users with existing corporate directories.
  • Client Adapters: Ready-to-use adapters for popular frameworks and programming languages (Java, JavaScript, Node.js, Python, etc.) accelerate Keycloak integration into your applications.
  • Theming: Full customization of the look and feel of login, registration, and account management pages to match your brand identity.

Advantages of Keycloak self-hosted on a VPS

Choosing a VPS for deploying Keycloak as Keycloak self-hosted offers several key advantages not available with cloud services or shared hosting:

  • Full Control: You have complete control over the entire infrastructure, from the operating system to Keycloak configuration and the database. This is critical for regulatory compliance and specific security settings.
  • Flexibility and Customization: A VPS allows you to install any additional services, modify configurations, and adapt Keycloak to your project's unique requirements. You can choose software versions, patches, and extensions without limitations.
  • Cost Savings: For medium to large projects, Keycloak on a server on a VPS is often significantly cheaper than paid cloud IAM solutions, especially for long-term use. You only pay for the resources you actually use.
  • Performance: Dedicated VPS resources guarantee predictable performance, which is crucial for an authentication system that must always be available and respond quickly. You can choose high-performance NVMe drives and powerful processors.
  • Security: You manage the security of your infrastructure yourself, including network settings, firewalls, and updates. This allows you to implement security policies that may not be available from third-party providers.
  • Scalability: As your project grows, you can easily scale VPS resources (CPU, RAM, disk) or even migrate to a dedicated server, while maintaining the same Keycloak architecture.

This approach provides not only independence but also the ability for deep optimization for specific tasks, whether it's a small corporate application or a large multi-user service.

Keycloak System Requirements: Which VPS to choose?

Choosing the right Keycloak VPS is critically important for ensuring stable and fast operation of your authentication system. Resource requirements depend on the expected load: the number of active users, authentication frequency, integration complexity, and the volume of stored data.

Minimum Requirements for a Test Environment

For development, testing, or very small projects with minimal load (up to 10-20 concurrent users, a few hundred authentications per day), modest resources are sufficient:

  • Processor (CPU): 1-2 vCPU. Keycloak can utilize multiple cores, but for minimal load, a single core with a good frequency (2.0+ GHz) will suffice.
  • Random Access Memory (RAM): 2 GB. Keycloak, being a Java application, requires sufficient memory. 2 GB is the absolute minimum for stable operation with the OS and database. It is recommended to allocate about 1-1.5 GB for the JVM.
  • Disk Space: 20-30 GB NVMe/SSD. NVMe will significantly speed up startup and database operations, but a regular SSD is fine for testing. The main volume is needed for the OS, Docker images, Keycloak itself, and the database.
  • Operating System: Ubuntu Server 22.04+, Debian 11+, CentOS Stream 9+. Lightweight distributions are preferred.
  • Database: Embedded H2 (for testing only!) or external PostgreSQL/MySQL. H2 is strictly not suitable for production.

For example, a VPS from Valebyte with 2 vCPU, 2 GB RAM, and 40 GB NVMe disk (costing around $5-10/month) will be perfectly sufficient to start.

Recommendations for a Production Environment

For a production environment, where reliability, performance, and scalability are important, resource requirements significantly increase. Here we will talk about Keycloak on a server that can withstand real-world load.

  • Processor (CPU): 2-4 vCPU (or more) with a frequency of 2.5+ GHz. Keycloak actively uses CPU for encryption, password hashing, and request processing. For 100-200 concurrent users and 50-100 requests per second (RPS), 2-4 vCPU will be a good start.
  • Random Access Memory (RAM): 4-8 GB. For stable operation of Keycloak and PostgreSQL (recommended DB), at least 4 GB is required, and 8 GB is better. This will allow the JVM to run comfortably, cache data, and avoid swapping.
  • Disk Space: 50-100 GB NVMe. NVMe disks are critically important for Keycloak database performance. A larger volume will provide space for logs, backups, and database growth.
  • Operating System: Ubuntu Server 22.04+ LTS. Stable, well-supported, and with extensive documentation.
  • Database: PostgreSQL 13+ (recommended) or MySQL 8+. Deploy it either in a separate container on the same VPS or on a separate database instance for high availability and performance.

When choosing a VPS, always consider the possibility of quickly upgrading resources. Valebyte offers flexible plans that allow you to easily scale CPU, RAM, and disk space as your Keycloak on a server needs grow.

Looking for a reliable server for your projects?

VPS from $10/month and dedicated servers from $9/month with NVMe, DDoS protection, and 24/7 support.

View offers →

Preparing your VPS for Keycloak Installation: Basic Steps

Before proceeding with Keycloak installation, you need to thoroughly prepare your VPS. This includes choosing an operating system, updating packages, configuring the firewall, and installing Docker — the main tool for deploying Keycloak.

Choosing an Operating System and Initial Setup

For Keycloak, it is recommended to use stable and well-supported Linux distributions. The most popular and convenient for administration are:

  • Ubuntu Server LTS: 22.04 LTS (Jammy Jellyfish) or newer is recommended. It features good documentation, a large community, and frequent security updates.
  • Debian Stable: Versions 11 (Bullseye) or 12 (Bookworm). Known for its stability and minimalism.

After deploying your VPS, perform the following basic steps:

  1. Connect via SSH:
    ssh root@your_vps_ip_address
  2. Update the system: Always start by updating all installed packages to the latest versions. This ensures you have the freshest security patches and bug fixes.
    sudo apt update && sudo apt upgrade -y
    (For Debian/Ubuntu)
    sudo dnf update -y
    (For CentOS Stream/Rocky Linux)
  3. Configure firewall (UFW for Ubuntu): Enable the firewall and allow only necessary ports (SSH, HTTP, HTTPS).
    sudo ufw enable
    sudo ufw allow ssh
    sudo ufw allow http
    sudo ufw allow https
    sudo ufw status
  4. Create a regular user (optional, but recommended): Working as root is not always secure. Create a new user and grant them sudo privileges.
    adduser your_user
    usermod -aG sudo your_user
    su - your_user

Installing Docker and Docker Compose

Keycloak will be deployed in Docker containers, which simplifies management, isolation, and scaling. Containers allow easy portability of the application between environments and ensure consistency. Docker Compose will help us define and run a multi-container application.

  1. Install Docker Engine: The official Docker installation script is the easiest way.
    sudo apt install ca-certificates curl gnupg -y
    sudo install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    sudo chmod a+r /etc/apt/keyrings/docker.gpg
    echo \
      "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
      "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
      sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt update
    sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y
    Verify Docker installation:
    sudo docker run hello-world
    If you are not working as root, add the user to the docker group:
    sudo usermod -aG docker your_user
    newgrp docker
    (Log out and log in again or use newgrp docker to apply changes.)
  2. Install Docker Compose: Docker Compose is now installed as a plugin to Docker, so the docker-compose-plugin command from the previous step has already installed it. Check Docker Compose version:
    docker compose version
    You should see something like Docker Compose version v2.x.x.

Your VPS is ready for Keycloak deployment. Now we can proceed to create the Docker Compose configuration and launch Keycloak.

rocket_launch Quick pick

Need a dedicated server?

Compare prices from top providers. Configure and order in minutes.

Browse dedicated servers arrow_forward

Step-by-Step Keycloak Installation on VPS with Docker Compose

Deploying Keycloak using Keycloak Docker and Docker Compose is the most recommended and flexible installation method. It allows easy management of dependencies (e.g., database), environment configuration, and component updates.

Creating the docker-compose.yml file for Keycloak

We will create a docker-compose.yml file that will describe two services: Keycloak and a PostgreSQL database. PostgreSQL is recommended as a stable and performant database for production environments.

Create a directory for your Keycloak project and navigate into it:

mkdir ~/keycloak
cd ~/keycloak

Create the docker-compose.yml file:

nano docker-compose.yml

And paste the following content. Make sure you replace YOUR_KEYCLOAK_ADMIN_PASSWORD and YOUR_POSTGRES_PASSWORD with strong passwords.

version: '3.8'

services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    container_name: keycloak
    environment:
      KEYCLOAK_ADMIN: admin
      KEYCLOAK_ADMIN_PASSWORD: YOUR_KEYCLOAK_ADMIN_PASSWORD
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://db:5432/keycloak
      KC_DB_USERNAME: keycloak
      KC_DB_PASSWORD: YOUR_POSTGRES_PASSWORD
      KC_HOSTNAME: auth.yourdomain.com # Replace with your domain
      KC_HTTP_PORT: 8080
      KC_HTTPS_PORT: 8443
      KC_PROXY: edge # Important for reverse proxy operation
      KC_HEALTH_ENABLED: true
      KC_METRICS_ENABLED: true
      # The following parameters for production optimization:
      KC_FEATURES: token-exchange,admin-fine-grained-authz
      KC_LOG_LEVEL: INFO
      KC_OPTIMIZED: 'true' # Enables optimization for production
    ports:
      - "8080:8080" # Keycloak internal port, will be proxied by Nginx/Caddy
      - "8443:8443" # Keycloak HTTPS port (for direct access, if no proxy)
    volumes:
      - ./keycloak_data:/opt/keycloak/data # For storing Keycloak data (cache, logs, etc.)
    depends_on:
      - db
    restart: always

  db:
    image: postgres:15-alpine
    container_name: keycloak_db
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: YOUR_POSTGRES_PASSWORD
    volumes:
      - ./postgres_data:/var/lib/postgresql/data # For persistent database storage
    restart: always
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U keycloak -d keycloak"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  keycloak_data:
  postgres_data:

Explanation of the docker-compose.yml file:

  • image: quay.io/keycloak/keycloak:latest: Uses the official Keycloak image. It is recommended to use a specific version instead of latest for production.
  • KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD: Credentials for the first login to the administrative console. Be sure to change the password!
  • KC_DB, KC_DB_URL, KC_DB_USERNAME, KC_DB_PASSWORD: PostgreSQL database connection settings.
  • KC_HOSTNAME: Very important parameter. Specify the domain name through which Keycloak will be accessible (e.g., auth.yourdomain.com). This is necessary for correct URL generation in Keycloak.
  • KC_PROXY: edge: This parameter tells Keycloak that it is running behind a reverse proxy (Nginx/Caddy) that will handle SSL.
  • KC_OPTIMIZED: 'true': Enables optimizations for the production environment, such as pre-compiling templates and caching.
  • ports: We open ports 8080 and 8443. In production, access to them will be through a reverse proxy, so they can be restricted by the firewall to localhost only.
  • volumes: We use named volumes (keycloak_data, postgres_data) for persistent data storage. This means that your data will not be lost when containers are restarted or updated.
  • depends_on: - db: Indicates that the keycloak service depends on the db service and will be started after it.
  • healthcheck for db: Ensures that Keycloak will not attempt to connect to the database until it is fully started and ready to accept connections.

Launching and Initial Keycloak Setup

After creating the docker-compose.yml file, you can start Keycloak:

docker compose up -d

The -d option runs the containers in the background. The startup process may take several minutes, especially on the first launch, as Docker will download images and Keycloak will perform initial database setup.

You can check the status of the containers:

docker compose ps

And view Keycloak logs to ensure it started successfully:

docker compose logs -f keycloak

Wait for the message that Keycloak has successfully started. After that, Keycloak will be accessible at http://your_vps_ip_address:8080. You can log into the administrative console at http://your_vps_ip_address:8080/admin, using the credentials admin and YOUR_KEYCLOAK_ADMIN_PASSWORD that you specified in docker-compose.yml.

Important: Direct access via IP:port without HTTPS is highly discouraged for production environments. In the next step, we will configure a reverse proxy and HTTPS.

Configuring Reverse Proxy (Nginx/Caddy) and HTTPS for Keycloak

To ensure the security and availability of Keycloak in a production environment, it is necessary to use a reverse proxy and HTTPS. A reverse proxy (e.g., Nginx or Caddy) will accept all incoming requests on standard ports (80 for HTTP and 443 for HTTPS), forward them to the Keycloak container, and handle SSL certificates. This allows hiding Keycloak's internal port and ensuring traffic encryption.

Configuring Nginx as a Reverse Proxy

Nginx is a powerful and widely used web server that is excellent for acting as a reverse proxy. Install Nginx if it is not already installed:

sudo apt install nginx -y

Create a new configuration file for your domain (e.g., auth.yourdomain.com) in the /etc/nginx/sites-available/ directory:

sudo nano /etc/nginx/sites-available/keycloak.conf

Paste the following content, replacing auth.yourdomain.com with your actual domain:

server {
    listen 80;
    server_name auth.yourdomain.com; # Replace with your domain

    location / {
        proxy_pass http://127.0.0.1:8080; # Keycloak runs on port 8080
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_max_temp_file_size 0;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
        proxy_connect_timeout 300s;

        # For WebSocket (if Keycloak uses them, e.g., for admin console)
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

Create a symbolic link to this file from sites-enabled so Nginx starts using it:

sudo ln -s /etc/nginx/sites-available/keycloak.conf /etc/nginx/sites-enabled/

Remove the default Nginx config to avoid conflicts:

sudo rm /etc/nginx/sites-enabled/default

Check Nginx configuration syntax and reload it:

sudo nginx -t
sudo systemctl reload nginx

Now your Keycloak should be accessible via HTTP at http://auth.yourdomain.com.

Obtaining and Automatically Renewing SSL Certificates with Let's Encrypt

To activate HTTPS, we will use Certbot and Let's Encrypt, which provide free and automated SSL certificates. Install Certbot and its Nginx plugin:

sudo apt install certbot python3-certbot-nginx -y

Run Certbot to obtain a certificate and automatically configure Nginx:

sudo certbot --nginx -d auth.yourdomain.com

Certbot will ask a few questions: provide your email, agree to the terms, and choose whether you want to force HTTP to HTTPS redirection (recommended).

After successful execution, Certbot will automatically update your Nginx configuration, adding HTTPS settings. Check Certbot's automatic renewal:

sudo systemctl status certbot.timer

This will show that Certbot is configured to automatically renew certificates before they expire. Now your Keycloak will be accessible at https://auth.yourdomain.com, and all traffic will be encrypted.

Alternative: Caddy for Simplicity

If you are looking for a simpler reverse proxy solution with automatic HTTPS, Caddy is an excellent choice. It automatically obtains and renews SSL certificates for specified domains. Install Caddy:

sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy -y

Create the Caddyfile:

sudo nano /etc/caddy/Caddyfile

And paste the following content, replacing auth.yourdomain.com with your domain:

auth.yourdomain.com {
    reverse_proxy 127.0.0.1:8080 {
        header_up Host {host}
        header_up X-Real-IP {remote_ip}
        header_up X-Forwarded-For {remote_ip}
        header_up X-Forwarded-Proto {scheme}
        header_up X-Forwarded-Host {host}
        header_up X-Forwarded-Port {server_port}
        transport http {
            keepalive_interval 30s
            read_timeout 300s
            write_timeout 300s
        }
    }
}

Check Caddy configuration and restart it:

sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl restart caddy

Caddy will automatically obtain an SSL certificate and configure HTTPS for your domain. This significantly simplifies setup compared to Nginx+Certbot, but Nginx can offer more flexibility for advanced configurations.

Keycloak Maintenance: Backups, Updates, and Monitoring

After successful Keycloak installation on a Keycloak VPS, it is crucial to ensure its proper maintenance. This includes regular data backups, timely updates, and continuous monitoring of performance and availability. These steps guarantee the reliability and security of your authentication system.

Keycloak Database Backup Strategies

Keycloak data is primarily stored in the database (users, roles, clients, sessions). Therefore, database backup is the most critical aspect. We use PostgreSQL, so we will focus on its tools.

Option 1: Backup from within the PostgreSQL container

This is the most direct method. Execute the following command on your VPS:

docker exec keycloak_db pg_dumpall -U keycloak > ~/keycloak_backup/keycloak_db_$(date +%Y%m%d%H%M%S).sql

Explanations:

  • docker exec keycloak_db: Executes the command inside the database container named keycloak_db.
  • pg_dumpall -U keycloak: PostgreSQL utility for creating a full dump of all databases. -U keycloak specifies the database user.
  • > ~/keycloak_backup/keycloak_db_$(date +%Y%m%d%H%M%S).sql: Redirects the output to a file with a unique name containing a timestamp.

Option 2: Backup using Docker Compose (to create a dump from a service)

You can add a separate backup service to your docker-compose.yml or execute the command manually:

docker compose exec db pg_dumpall -U keycloak > ~/keycloak_backup/keycloak_db_$(date +%Y%m%d%H%M%S).sql

Backup Recommendations:

  1. Automation: Set up a cron job to automatically perform backups daily or several times a day, depending on the frequency of changes and RPO (Recovery Point Objective) requirements.
    0 3 * * * docker exec keycloak_db pg_dumpall -U keycloak > /root/keycloak_backup/keycloak_db_$(date +\%Y\%m\%d\%H\%M\%S).sql
    (This command will perform a backup at 03:00 every day.)
  2. Storage: Store backups not only on the same VPS but also on external storage (S3, Dropbox, another server) to protect against complete VPS failure.
  3. Rotation: Implement a backup rotation policy to avoid filling up the disk (e.g., keep backups for the last 7 days).
  4. Verification: Periodically verify the integrity of backups by restoring them on a test server.

Keycloak Container Update Process

Updating Keycloak deployed via Docker Compose is relatively simple but requires caution and prior testing.

  1. Create a backup: Before any update, always make a full backup of the Keycloak database.
  2. Stop current containers:
    cd ~/keycloak # Navigate to the directory with docker-compose.yml
    docker compose down
  3. Update Keycloak image: Change the image tag in docker-compose.yml from :latest to a new, specific version (e.g., :22.0.5). Then pull the new image:
    docker compose pull keycloak
  4. Start updated containers:
    docker compose up -d
    Keycloak will automatically apply necessary database migrations on the first startup of the new version.
  5. Check logs: Ensure Keycloak started without errors:
    docker compose logs -f keycloak
  6. Verify functionality: Log into the administrative console and test basic authentication and authorization functions.

Important: Always read the official Keycloak upgrade documentation before performing an upgrade, as there may be changes between major versions that require additional actions.

Performance and Availability Monitoring

Monitoring Keycloak on a server is essential for timely problem detection, preventing downtime, and optimizing resources.

Key metrics for monitoring:

  • Service availability: Check if Keycloak responds to requests (e.g., via ping or HTTP request to the /auth/realms/master/.well-known/openid-configuration endpoint).
  • CPU usage: High CPU load can indicate insufficient resources or inefficient queries.
  • RAM usage: Monitor Keycloak and database memory consumption. If it approaches the limit, it can lead to slowdowns or crashes.
  • Disk I/O operations (IOPS): High IOPS values, especially on the database disk, can indicate a disk subsystem bottleneck.
  • Database metrics: Query execution time, number of active connections, database size.
  • Keycloak logs: Regularly review logs for errors, warnings, or suspicious activity.

Monitoring tools:

  • Netdata: An excellent tool for real-time VPS resource monitoring. It's easy to install and provides detailed graphs for CPU, RAM, disk, network, and Docker containers. You can learn more about installing Netdata on a VPS in our article.
  • Prometheus and Grafana: A more advanced solution for collecting, storing, and visualizing metrics. Keycloak provides endpoints for Prometheus (/health and /metrics, if KC_HEALTH_ENABLED and KC_METRICS_ENABLED are enabled).
  • Log aggregators: For collecting and analyzing logs from all containers, use solutions like ELK Stack (Elasticsearch, Logstash, Kibana) or Loki+Grafana.

Regular monitoring will allow you to respond promptly to issues and maintain a high level of reliability for your IAM system.

rocket_launch Quick pick

Need a dedicated server?

Compare prices from top providers. Configure and order in minutes.

Browse dedicated servers arrow_forward

Optimal VPS Configuration for Keycloak Under Real Load

Choosing the right Keycloak VPS configuration is key to ensuring stable performance and scalability under real load. Insufficient resources will lead to slowdowns, errors, and failures, while excessive resources will result in unnecessary costs. The optimal choice depends on the number of users, the expected number of requests per second (RPS), and other factors.

Analysis of Factors Affecting Performance

When determining the necessary VPS configuration for Keycloak, consider the following factors:

  • Number of active users: How many users will simultaneously authenticate or manage their accounts.
  • Authentication frequency (RPS): The number of login requests per second. This is one of the most resource-intensive processes.
  • Authentication type: Simple username/password logins are less demanding than MFA, federated authentication via LDAP, or complex authorization policies.
  • Number of clients/applications: The more clients integrated with Keycloak, the more resources may be required for their management and token issuance.
  • Caching usage: Effective caching significantly reduces database and CPU load.
  • Data volume: The number of users, groups, roles, and sessions stored in the database. A large database requires more disk space and can affect query speed.
  • Additional services: If other applications or services will run on the same VPS, their requirements must also be considered.

Keycloak, being a Java application, and PostgreSQL actively use CPU and RAM. The disk subsystem must be fast (NVMe) for the database.

For a more detailed VPS selection, pay attention to virtualization types, such as KVM, which provide more isolated and performant resources compared to OpenVZ. You can learn more about this in the article KVM VPS vs OpenVZ VPS in 2026.

Table: Recommended VPS Configuration for Keycloak

Below is a table with recommendations for Keycloak VPS configuration depending on the anticipated load. These are general recommendations that may vary depending on the specifics of your Keycloak usage and JVM settings.

Load Scenario Active Users (concurrent) RPS (requests per second) vCPU RAM (GB) Disk (NVMe/SSD) Estimated VPS Cost (Valebyte.com)
Development/Test/Minimal Up to 20 Up to 5 2 2-4 40 GB NVMe $5 - $10/month
Small Business/Startup 50 - 200 10 - 30 2-4 4-8 60-80 GB NVMe $10 - $25/month
Medium Business/Growing Project 200 - 1000 30 - 100 4-8 8-16 100-200 GB NVMe $25 - $60/month
Large Business/High Load 1000 - 5000+ 100 - 300+ 8-16+ 16-32+ 200-500 GB NVMe $60 - $150+/month

Additional Considerations:

  • High Availability: For mission-critical systems, consider a clustered Keycloak deployment on multiple VPS instances with a load balancer.
  • Separate Database: For very high loads or to ensure greater reliability, the PostgreSQL database can be moved to a separate VPS or a managed database service.
  • Network: Ensure your VPS provider offers a stable and fast network infrastructure.
  • Self-Managed VPS: Managing Keycloak on a server requires certain system administration skills. If you prefer full control and are ready for self-support, a self-managed VPS is your choice.

These recommendations will help you make an informed decision when renting a Keycloak VPS that will meet your current and future needs.

Possible Problems and Their Solutions When Working with Keycloak on a VPS

Even with careful installation and configuration, problems can arise when working with Keycloak on a VPS. Knowing common errors and how to troubleshoot them will help quickly restore system functionality.

Common Startup and Access Errors

  1. Keycloak does not start / Database connection error:
    • Cause: Incorrect database credentials, database not running, network issues between Keycloak and the DB.
    • Solution: Check Keycloak container logs (docker compose logs keycloak) and DB container logs (docker compose logs db). Ensure that KC_DB_URL, KC_DB_USERNAME, KC_DB_PASSWORD in docker-compose.yml match your PostgreSQL settings. Check the DB container status (docker compose ps) and its healthcheck.
  2. Keycloak access by domain not working (404 Not Found, 502 Bad Gateway):
    • Cause: Incorrect Nginx/Caddy configuration, DNS records not pointing to the VPS, firewall blocking ports.
    • Solution: Ensure your DNS record (A-record for auth.yourdomain.com) points to your VPS IP. Check Nginx/Caddy configuration (sudo nginx -t, sudo caddy validate) and restart them. Make sure ports 80 and 443 are open in the VPS firewall (sudo ufw status). Verify that the Keycloak container is listening on port 8080.
  3. HTTPS issues / Invalid SSL certificate:
    • Cause: Certbot failed to obtain a certificate, domain not resolving, incorrect Nginx/Caddy configuration for SSL.
    • Solution: Ensure your domain correctly points to the VPS IP and is accessible on port 80 (Certbot uses it for verification). Try reissuing the certificate (sudo certbot --nginx -d auth.yourdomain.com). Check Nginx/Caddy configuration for errors.
  4. Keycloak throws "Invalid redirect URI" or "Invalid parameter: redirect_uri" error:
    • Cause: Incorrect KC_HOSTNAME configured in docker-compose.yml or "Valid Redirect URIs" are incorrectly specified in the client settings in Keycloak.
    • Solution: Ensure that KC_HOSTNAME matches the domain through which Keycloak is externally accessible (e.g., auth.yourdomain.com). In the Keycloak administrative console, for each client, go to "Clients" -> "Your client" -> "Settings" and add all correct redirect URLs to the "Valid Redirect URIs" field. For example, https://your_app.com/*.
  5. Slow Keycloak performance:
    • Cause: Insufficient VPS resources (CPU, RAM, IOPS), unoptimized JVM settings, inefficient database queries.
    • Solution: Check VPS resource utilization using monitoring tools (e.g., Netdata). Consider upgrading your VPS to a more powerful plan. Increase allocated JVM memory (JAVA_OPTS: -Xmx4g in docker-compose.yml). Optimize Keycloak caching settings.

Performance Optimization: Tips and Tricks

  • Increase JVM Heap Size: Keycloak, being a Java application, benefits from sufficient memory. Add to the environment section for the keycloak service in docker-compose.yml:
    JAVA_OPTS: "-Xmx4096m -Xms2048m"
    (where 4096m = 4GB, 2048m = 2GB. Adjust according to available RAM on your VPS).
  • Enable Caching: Ensure Keycloak caching is active. By default, it is reasonably configured, but can be fine-tuned via JGroups if necessary.
  • Use NVMe Disks: For the database and Keycloak data, NVMe disks provide significantly higher performance compared to regular SSDs or HDDs, which is critical for fast read/write operations.
  • Optimize the Database: Regularly perform VACUUM ANALYZE for PostgreSQL to maintain query performance. Consider indexing frequently used fields.
  • Disable Unnecessary Features: If you are not using certain Keycloak features (e.g., federation, social logins), disabling them can slightly reduce resource consumption.
  • Monitoring and Profiling: Use monitoring tools (like Netdata) to identify bottlenecks. For deep analysis of Java application performance, you can use JMX monitoring or profilers.
  • Scaling: For very high loads, consider horizontal scaling of Keycloak (multiple instances behind a load balancer) and offloading the database to a separate high-performance server or managed service.

Regular maintenance, monitoring, and timely optimization will help you keep Keycloak running smoothly and ensure high performance for your authentication system.

Conclusion

Installing and configuring Keycloak on a VPS using Docker Compose is a powerful and cost-effective solution for centralized identity and access management. You gain full control over your IAM infrastructure, configuration flexibility, and scalability, making Keycloak self-hosted on a VPS an ideal choice for most projects.

Choosing the optimal Keycloak VPS configuration, regular backups, and active monitoring are key factors for success. Valebyte.com offers reliable VPS servers with NVMe disks and flexible configurations, perfectly suited for deploying Keycloak of any scale, from a test environment to a high-load production setup.

Ready to choose a server?

VPS and dedicated servers in 72+ countries with instant activation and full root access.

Get started now →
support_agent
Valebyte Support
Usually replies within minutes
Hi there!
Send us a message and we'll reply as soon as possible.