# Keycloak

> Open source identity and access management.

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

## Overview

Keycloak is an open-source identity and access management solution originally developed by Red Hat that provides enterprise-grade authentication and authorization services. Born from the need to simplify complex identity management across distributed applications, Keycloak supports modern protocols like OpenID Connect, OAuth 2.0, and SAML 2.0, making it a cornerstone for implementing single sign-on (SSO) and centralized user management in modern architectures.

This stack combines Keycloak with PostgreSQL to create a robust identity management platform where PostgreSQL serves as the production-grade database backend for storing user credentials, sessions, and configuration data. Unlike Keycloak's default H2 database which is suitable only for development, PostgreSQL provides the reliability, performance, and scalability needed for production identity workloads with proper ACID compliance and concurrent user support.

This combination is ideal for organizations transitioning from development to production identity management, enterprises implementing SSO across multiple applications, and development teams building microservices that require centralized authentication. The PostgreSQL backend ensures data integrity for critical identity data while Keycloak's flexible realm and client model allows you to manage multiple applications and user groups from a single control plane.

## Features

- Multi-realm architecture for tenant isolation and organizational boundaries
- OpenID Connect and OAuth 2.0 support for modern application integration
- Social login integration with Google, Facebook, GitHub, and other providers
- User federation with LDAP and Active Directory for enterprise environments
- Fine-grained role-based access control with custom attributes and policies
- Customizable login themes and user registration flows
- PostgreSQL backend with ACID compliance for reliable identity data storage
- Built-in admin console for realm management and user administration

## Use cases

- Enterprise SSO implementation across internal web applications and services
- Microservices authentication with JWT token validation and user context
- Customer identity management for SaaS platforms with multi-tenant requirements
- API security with OAuth 2.0 client credentials and access token validation
- Legacy application modernization by adding OIDC authentication layers
- Development environment identity services for testing authentication flows
- Homelab central authentication for self-hosted services like Grafana and GitLab

## Prerequisites

- Minimum 1.5GB RAM available (1GB for Keycloak, 512MB for PostgreSQL)
- Port 8080 available for Keycloak web interface and API access
- Basic understanding of OAuth 2.0/OIDC concepts and token-based authentication
- Familiarity with realm and client configuration in identity management systems
- Docker Compose environment with persistent volume support for database storage

## docker-compose.yml

```yaml
services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    container_name: keycloak
    command: start-dev
    environment:
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://postgres:5432/${DB_NAME}
      KC_DB_USERNAME: ${DB_USER}
      KC_DB_PASSWORD: ${DB_PASSWORD}
      KEYCLOAK_ADMIN: ${ADMIN_USER}
      KEYCLOAK_ADMIN_PASSWORD: ${ADMIN_PASSWORD}
    ports:
      - "8080:8080"
    depends_on:
      - postgres
    networks:
      - keycloak

  postgres:
    image: postgres:16-alpine
    container_name: keycloak-postgres
    environment:
      POSTGRES_DB: ${DB_NAME}
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - keycloak

volumes:
  postgres_data:

networks:
  keycloak:
    driver: bridge
```

## .env

```bash
DB_NAME=keycloak
DB_USER=keycloak
DB_PASSWORD=changeme
ADMIN_USER=admin
ADMIN_PASSWORD=changeme
```

## Usage notes

- Docs: https://www.keycloak.org/documentation
- Admin console at http://localhost:8080/admin
- Create realm for each app/org, then clients within realms
- For production: use 'start' instead of 'start-dev', add KC_HOSTNAME
- OIDC endpoint: /realms/{realm}/.well-known/openid-configuration
- Export realm: docker exec keycloak /opt/keycloak/bin/kc.sh export

## Troubleshooting

- Keycloak fails to start with database connection errors: Verify PostgreSQL container is healthy and database credentials match between services
- Admin console shows 'Invalid credentials' after setup: Check KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD environment variables are properly set
- Applications can't reach OIDC endpoints: Ensure Keycloak is accessible at the hostname configured in your client applications, not just localhost
- User sessions not persisting after container restart: Verify postgres_data volume is properly mounted and PostgreSQL is storing session data
- High memory usage and slow performance: Increase Keycloak container memory limit and tune PostgreSQL shared_buffers for your user load
- Realm export/import fails with permission errors: Run export commands with proper user permissions inside the container using docker exec

