# Keycloak Identity Management

> Enterprise-grade identity and access management solution.

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

## Overview

Keycloak is an open-source identity and access management solution originally developed by Red Hat, designed to provide enterprise-grade authentication and authorization capabilities. It supports modern protocols like OpenID Connect, OAuth 2.0, and SAML 2.0, enabling single sign-on (SSO) across multiple applications while maintaining centralized user management. Keycloak has become the go-to choice for organizations seeking a self-hosted alternative to cloud-based identity providers like Auth0 or Okta.

This stack combines Keycloak with PostgreSQL as a production-ready database backend and NGINX as a reverse proxy for SSL termination and load balancing. PostgreSQL provides ACID compliance and robust data integrity for storing user credentials, sessions, and configuration data, while NGINX handles incoming requests and can distribute traffic across multiple Keycloak instances. This architecture ensures high availability and performance for enterprise authentication workloads.

This configuration is ideal for organizations implementing zero-trust security models, modernizing legacy applications with modern authentication, or building microservices architectures requiring centralized identity management. The stack provides enterprise-level security features while remaining completely self-hosted, giving organizations full control over their identity infrastructure without vendor lock-in or per-user licensing costs.

## Features

- Single Sign-On (SSO) with OpenID Connect, OAuth 2.0, and SAML 2.0 protocol support
- Identity brokering for social logins (Google, GitHub, Facebook) and enterprise identity providers
- User federation with LDAP and Active Directory integration for existing user stores
- Multi-tenancy support through realms for isolating different applications or organizations
- Fine-grained authorization with role-based and attribute-based access control
- Administrative console with REST APIs for programmatic realm and user management
- PostgreSQL backend providing ACID compliance and data integrity for identity data
- NGINX reverse proxy with SSL termination and load balancing capabilities

## Use cases

- Enterprise SSO implementation for modernizing authentication across legacy and new applications
- Microservices authentication gateway providing JWT token validation and user context
- Multi-tenant SaaS platforms requiring isolated user management per customer organization
- API security layer protecting REST APIs with OAuth 2.0 scopes and client credentials
- Hybrid cloud identity bridge connecting on-premises Active Directory with cloud applications
- Development platform authentication for internal tools, CI/CD systems, and developer portals
- Healthcare and financial services requiring HIPAA/SOX compliant identity management

## Prerequisites

- Minimum 2GB RAM recommended (1GB for Keycloak, 512MB for PostgreSQL, 256MB for NGINX)
- Available ports 80, 443 (NGINX), and 8080 (Keycloak admin console)
- Basic understanding of OAuth 2.0, OpenID Connect, and JWT token concepts
- SSL certificates for production deployment (self-signed acceptable for development)
- Knowledge of PostgreSQL administration for backup and maintenance procedures
- Familiarity with NGINX configuration for customizing reverse proxy rules

## docker-compose.yml

```yaml
services:
  keycloak:
    image: quay.io/keycloak/keycloak:latest
    ports:
      - "8080:8080"
    environment:
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://postgres:5432/${POSTGRES_DB}
      KC_DB_USERNAME: ${POSTGRES_USER}
      KC_DB_PASSWORD: ${POSTGRES_PASSWORD}
      KEYCLOAK_ADMIN: ${KEYCLOAK_ADMIN}
      KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD}
      KC_HOSTNAME: localhost
      KC_HOSTNAME_PORT: 8080
      KC_HTTP_ENABLED: "true"
    command: start-dev
    depends_on:
      postgres:
        condition: service_healthy
    networks:
      - keycloak-net
    restart: unless-stopped

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - keycloak-net
    restart: unless-stopped

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./certs:/etc/nginx/certs:ro
    depends_on:
      - keycloak
    networks:
      - keycloak-net
    restart: unless-stopped

volumes:
  postgres_data:

networks:
  keycloak-net:
    driver: bridge
```

## .env

```bash
# PostgreSQL
POSTGRES_USER=keycloak
POSTGRES_PASSWORD=secure_postgres_password
POSTGRES_DB=keycloak

# Keycloak Admin
KEYCLOAK_ADMIN=admin
KEYCLOAK_ADMIN_PASSWORD=secure_admin_password
```

## Usage notes

- Keycloak Admin at http://localhost:8080
- Create realms, clients, and users
- Supports OIDC, OAuth2, SAML
- Use 'start' instead of 'start-dev' for production

## Troubleshooting

- Keycloak fails to start with database connection error: Verify PostgreSQL container is healthy and POSTGRES_* environment variables match between services
- Admin console shows 'Invalid request' after login: Check KC_HOSTNAME and KC_HOSTNAME_PORT match your actual access URL, update for production domains
- PostgreSQL container exits with 'role does not exist': Ensure POSTGRES_USER environment variable is set and matches KC_DB_USERNAME in Keycloak service
- NGINX returns 502 Bad Gateway: Verify Keycloak container is running and accessible on port 8080, check Docker network connectivity
- Keycloak themes not loading properly: Mount custom theme volumes to /opt/keycloak/themes/ and restart container
- High memory usage in production: Switch from 'start-dev' to 'start' command and configure KC_CACHE for clustering

