# Keycloak + PostgreSQL + Themes

> Enterprise identity and access management.

- Category: Security & Networking
- Difficulty: advanced
- Components: keycloak, postgresql
- Tags: keycloak, sso, identity, oauth2, saml, enterprise
- Source: https://docker.recipes/security/keycloak-complete

## Overview

Keycloak is an open-source identity and access management solution developed by Red Hat that provides enterprise-grade authentication and authorization services. Originally created in 2014, Keycloak has become the leading self-hosted alternative to commercial identity providers like Auth0 and Okta, offering single sign-on (SSO), identity brokering, user federation, and support for standard protocols including OAuth2, OpenID Connect, and SAML. Its comprehensive feature set includes multi-tenancy through realms, social login integration, LDAP/Active Directory federation, and fine-grained authorization policies.

This stack combines Keycloak with PostgreSQL as the backend database and includes support for custom themes, creating a robust and scalable identity management platform. PostgreSQL provides enterprise-grade data persistence with ACID compliance, ensuring user credentials, session data, and configuration remain consistent even under high load. The themes volume enables complete customization of login pages, admin console styling, and user-facing interfaces to match corporate branding requirements. This combination delivers production-ready identity services that can handle thousands of concurrent users while maintaining data integrity.

Enterprise architects, security teams, and organizations implementing microservices architectures should consider this stack when they need centralized authentication without vendor lock-in. The self-hosted nature provides complete control over user data and compliance requirements, while PostgreSQL's proven reliability makes it suitable for mission-critical identity services. Custom theme support makes this particularly valuable for customer-facing applications where brand consistency is essential, and the combination scales from small development teams to large enterprises managing multiple applications and user bases.

## Features

- Single Sign-On (SSO) with OAuth2, OpenID Connect, and SAML protocol support
- PostgreSQL backend ensuring ACID-compliant storage for user credentials and sessions
- Custom theme support with dedicated volume for login page and admin console branding
- Identity brokering for social logins (Google, Facebook, GitHub) and enterprise providers
- User federation with LDAP and Active Directory integration
- Multi-tenant realm architecture for isolating different applications or organizations
- Fine-grained authorization policies with role-based and attribute-based access control
- Admin REST API for programmatic user management and configuration

## Use cases

- Enterprise SSO implementation replacing legacy authentication systems across multiple applications
- Microservices architecture requiring centralized JWT token validation and user management
- Customer-facing applications needing branded login pages with social authentication options
- B2B SaaS platforms requiring multi-tenant user isolation and custom identity provider integration
- Legacy application modernization where existing LDAP/AD infrastructure must be preserved
- Compliance-heavy environments requiring self-hosted identity management with audit trails
- Development teams building multiple applications that need shared user authentication and authorization

## Prerequisites

- Minimum 1.5GB RAM available (1GB for Keycloak, 512MB for PostgreSQL)
- Port 8080 available for Keycloak admin console and authentication endpoints
- Basic understanding of OAuth2/OpenID Connect flows for application integration
- Knowledge of PostgreSQL administration for backup and performance tuning
- Familiarity with Keycloak realm concepts and user federation if integrating existing directories
- Understanding of theme development using FreeMarker templates for custom branding

## docker-compose.yml

```yaml
services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    command: start
    environment:
      - KC_DB=postgres
      - KC_DB_URL=jdbc:postgresql://postgres:5432/keycloak
      - KC_DB_USERNAME=${POSTGRES_USER}
      - KC_DB_PASSWORD=${POSTGRES_PASSWORD}
      - KC_HOSTNAME=localhost
      - KC_HOSTNAME_STRICT=false
      - KC_HOSTNAME_STRICT_HTTPS=false
      - KC_HTTP_ENABLED=true
      - KC_PROXY=edge
      - KEYCLOAK_ADMIN=${ADMIN_USER}
      - KEYCLOAK_ADMIN_PASSWORD=${ADMIN_PASSWORD}
    volumes:
      - keycloak-themes:/opt/keycloak/themes
    ports:
      - "8080:8080"
    depends_on:
      - postgres
    networks:
      - keycloak-network
    restart: unless-stopped

  postgres:
    image: postgres:15
    environment:
      - POSTGRES_USER=${POSTGRES_USER}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
      - POSTGRES_DB=keycloak
    volumes:
      - postgres-data:/var/lib/postgresql/data
    networks:
      - keycloak-network
    restart: unless-stopped

volumes:
  keycloak-themes:
  postgres-data:

networks:
  keycloak-network:
    driver: bridge
```

## .env

```bash
# Keycloak
POSTGRES_USER=keycloak
POSTGRES_PASSWORD=secure_postgres_password
ADMIN_USER=admin
ADMIN_PASSWORD=secure_admin_password
```

## Usage notes

- Admin console at http://localhost:8080
- Create realms for apps
- OAuth2/OIDC and SAML
- LDAP federation
- Custom themes supported

## Troubleshooting

- Keycloak fails to start with database connection errors: Verify PostgreSQL container is healthy and POSTGRES_USER/POSTGRES_PASSWORD environment variables match between services
- Admin console shows 'Invalid redirect URI' errors: Add your application's callback URLs to the client configuration in the Keycloak admin console under Client Settings
- Custom themes not appearing in Keycloak: Ensure theme files are placed in correct directory structure within the keycloak-themes volume and restart the Keycloak container
- PostgreSQL connection pool exhaustion under load: Increase KC_DB_POOL_MAX_SIZE environment variable and tune PostgreSQL max_connections setting
- LDAP user federation sync failures: Check LDAP connection settings in Keycloak admin console and verify bind DN has sufficient privileges to read user attributes
- Token validation errors in applications: Confirm application is using correct realm endpoint URL and client secret, check Keycloak logs for specific JWT validation failures

