# SonarQube Code Quality

> SonarQube for continuous code quality inspection with PostgreSQL.

- Category: DevOps & CI/CD
- Difficulty: intermediate
- Components: sonarqube, postgresql
- Tags: sonarqube, code-quality, static-analysis, security, ci-cd
- Source: https://docker.recipes/devops/sonarqube-code-quality

## Overview

SonarQube is an enterprise-grade code quality and security analysis platform that performs continuous inspection of codebases through static analysis. Developed by SonarSource and actively maintained for over a decade, SonarQube detects bugs, code smells, security vulnerabilities, and technical debt across 30+ programming languages. It serves as a critical component in modern CI/CD pipelines, enforcing quality gates that prevent problematic code from reaching production environments.

This stack combines SonarQube with PostgreSQL to create a robust code analysis infrastructure. PostgreSQL serves as SonarQube's primary database, storing project configurations, analysis results, user permissions, and historical quality metrics. The relational database's ACID compliance ensures data integrity for critical quality measurements, while its advanced querying capabilities support SonarQube's complex reporting and trend analysis features. PostgreSQL's reliability makes it ideal for enterprise environments where code quality data must be preserved and accurately tracked over time.

This combination targets development teams implementing quality gates, DevOps engineers establishing CI/CD standards, and organizations requiring comprehensive security scanning. Unlike SaaS alternatives like CodeClimate, this self-hosted setup provides complete control over sensitive source code analysis while supporting custom rules and enterprise compliance requirements. The PostgreSQL backend enables sophisticated quality trend analysis and supports SonarQube's branch analysis features essential for modern Git workflows.

## Features

- Static code analysis across 30+ programming languages including Java, C#, JavaScript, Python, and Go
- Security vulnerability detection with OWASP Top 10 and CWE standards coverage
- Quality gates that automatically pass or fail builds based on configurable metrics
- Technical debt quantification with time-based estimates for remediation
- Branch analysis supporting pull request decoration and short-lived branch scanning
- Code smell detection identifying maintainability issues and anti-patterns
- PostgreSQL-backed trend analysis showing quality evolution over time
- Enterprise authentication integration with LDAP, SAML, and OAuth providers

## Use cases

- Enterprise development teams enforcing coding standards across multiple projects and languages
- CI/CD pipeline integration blocking deployments when code quality thresholds aren't met
- Security-focused organizations requiring automated vulnerability scanning before releases
- Large codebases needing technical debt tracking and refactoring prioritization
- Regulated industries maintaining code quality audit trails and compliance documentation
- Development teams implementing code review processes with automated quality checks
- Organizations migrating from commercial static analysis tools seeking open-source alternatives

## Prerequisites

- Minimum 4GB RAM available for SonarQube container (2GB absolute minimum for small projects)
- Docker host with at least 2 CPU cores for reasonable analysis performance
- Port 9000 available for SonarQube web interface access
- Understanding of static code analysis concepts and quality gate configuration
- Familiarity with your programming languages' specific SonarQube rules and plugins
- Basic knowledge of CI/CD integration for automated analysis triggering

## docker-compose.yml

```yaml
services:
  postgres:
    image: postgres:16-alpine
    container_name: sonarqube-postgres
    restart: unless-stopped
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-sonar}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-sonar}
      POSTGRES_DB: ${POSTGRES_DB:-sonarqube}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - sonar-network

  sonarqube:
    image: sonarqube:lts-community
    container_name: sonarqube
    restart: unless-stopped
    ports:
      - "${SONAR_PORT:-9000}:9000"
    environment:
      - SONAR_JDBC_URL=jdbc:postgresql://postgres:5432/${POSTGRES_DB:-sonarqube}
      - SONAR_JDBC_USERNAME=${POSTGRES_USER:-sonar}
      - SONAR_JDBC_PASSWORD=${POSTGRES_PASSWORD:-sonar}
    volumes:
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
    depends_on:
      - postgres
    networks:
      - sonar-network

volumes:
  postgres_data:
  sonarqube_data:
  sonarqube_extensions:
  sonarqube_logs:

networks:
  sonar-network:
    driver: bridge
```

## .env

```bash
# SonarQube
SONAR_PORT=9000
POSTGRES_USER=sonar
POSTGRES_PASSWORD=sonar
POSTGRES_DB=sonarqube
```

## Usage notes

- SonarQube at http://localhost:9000
- Default login: admin/admin
- Change password on first login
- Install language plugins as needed

## Troubleshooting

- SonarQube fails to start with 'Elasticsearch can not run as root': Ensure proper system configuration with vm.max_map_count=262144 on Docker host
- Analysis fails with 'OutOfMemoryError': Increase container memory limits or configure sonar.ce.javaOpts for compute engine heap size
- PostgreSQL connection refused during startup: Verify database credentials match between services and ensure postgres container starts before SonarQube
- Quality gate fails unexpectedly: Check project-specific quality profiles and ensure baseline/new code period is properly configured
- Plugin installation fails: Restart SonarQube container after installing plugins through the marketplace or manual upload
- Scanner execution timeout on large projects: Increase sonar.ws.timeout property and consider excluding test files or generated code from analysis

