# Keycloak Identity Management

> Open-source identity and access management with SSO, OAuth2, OIDC, and SAML support. PostgreSQL backend for production reliability.

- Category: Security & Networking
- Difficulty: intermediate
- Components: keycloak, postgresql
- Tags: keycloak, sso, oauth, identity, oidc, saml
- Source: https://docker.recipes/security/keycloak-identity-stack

## Overview

Keycloak is an open-source identity and access management solution developed by Red Hat that provides comprehensive authentication and authorization services for modern applications. Originally created to simplify single sign-on (SSO) implementation, Keycloak has evolved into a full-featured identity provider supporting industry-standard protocols including OAuth 2.0, OpenID Connect (OIDC), and SAML 2.0, making it essential for securing microservices architectures and enterprise applications.

This deployment consists of two services: a PostgreSQL 15 Alpine database (keycloak-db) for persistent storage and the Keycloak application server itself. The PostgreSQL backend provides production-grade data persistence for user accounts, roles, sessions, and configuration data, replacing Keycloak's default H2 embedded database. The setup includes health checks for reliable startup sequencing and exposes metrics endpoints for monitoring.

This configuration is ideal for organizations requiring self-hosted identity management with enterprise-grade database backing. Development teams building microservices, IT departments implementing SSO across multiple applications, and organizations with compliance requirements will benefit from this combination of Keycloak's flexible identity features and PostgreSQL's ACID-compliant data storage.

## Features

- Single Sign-On (SSO) with support for OAuth 2.0, OpenID Connect, and SAML 2.0 protocols
- Multi-tenant realm architecture for isolating different applications and user groups
- Identity brokering with social login providers (Google, Facebook, GitHub) and enterprise directories
- User federation capabilities for LDAP and Active Directory integration
- Fine-grained authorization policies with role-based and attribute-based access control
- Customizable login pages and authentication flows with theme support
- Built-in admin console with REST API for programmatic management
- PostgreSQL backend ensuring ACID compliance and reliable data persistence

## Use cases

- Enterprise single sign-on implementation across web applications and services
- Microservices authentication with centralized token management and validation
- API gateway security with OAuth 2.0 token introspection and validation
- Legacy application modernization by adding modern authentication protocols
- Multi-tenant SaaS platforms requiring isolated user management per customer
- Development environments needing realistic identity management for testing
- Organizations migrating from proprietary identity solutions to open-source alternatives

## Prerequisites

- Docker and Docker Compose installed with minimum 1.5GB available RAM
- Environment variables configured: DB_PASSWORD, ADMIN_USER, ADMIN_PASSWORD
- Port 8080 available for Keycloak web interface (customizable via KC_PORT)
- Basic understanding of OAuth 2.0/OIDC concepts for realm and client configuration
- Knowledge of PostgreSQL for database maintenance and backup procedures
- Understanding of identity management concepts like realms, roles, and scopes

## docker-compose.yml

```yaml
services:
  keycloak-db:
    image: postgres:15-alpine
    container_name: keycloak-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=keycloak
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=keycloak
    volumes:
      - keycloak_db_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U keycloak"]
      interval: 10s
      timeout: 5s
      retries: 5

  keycloak:
    image: quay.io/keycloak/keycloak:latest
    container_name: keycloak
    restart: unless-stopped
    ports:
      - "${KC_PORT:-8080}:8080"
    environment:
      - KC_DB=postgres
      - KC_DB_URL=jdbc:postgresql://keycloak-db:5432/keycloak
      - KC_DB_USERNAME=keycloak
      - KC_DB_PASSWORD=${DB_PASSWORD}
      - KEYCLOAK_ADMIN=${ADMIN_USER}
      - KEYCLOAK_ADMIN_PASSWORD=${ADMIN_PASSWORD}
      - KC_HEALTH_ENABLED=true
      - KC_METRICS_ENABLED=true
    command: start-dev
    depends_on:
      keycloak-db:
        condition: service_healthy

volumes:
  keycloak_db_data:
```

## .env

```bash
# Keycloak Configuration
KC_PORT=8080
ADMIN_USER=admin
ADMIN_PASSWORD=change_this_admin_password

# Database
DB_PASSWORD=keycloak_db_password
```

## Usage notes

- Access Keycloak at http://localhost:8080
- Admin console at http://localhost:8080/admin
- Create realms to isolate different applications
- For production, use 'start' instead of 'start-dev' and configure hostname
- Supports OAuth2, OIDC, SAML 2.0 protocols
- Health endpoint at /health, metrics at /metrics

## Troubleshooting

- keycloak container fails to start: Ensure DB_PASSWORD environment variable is set and matches between both services
- Database connection errors in keycloak logs: Verify keycloak-db service is healthy and PostgreSQL accepts connections on port 5432
- Admin console login fails: Check ADMIN_USER and ADMIN_PASSWORD environment variables are properly configured
- Slow startup times: Increase PostgreSQL shared_buffers and effective_cache_size, or allocate more RAM to containers
- Health check failures on keycloak-db: Ensure PostgreSQL service has sufficient time to initialize, increase healthcheck timeout if needed
- Memory issues during realm import: Increase container memory limits and consider using production mode with 'start' command instead of 'start-dev'

