Skip to content

Deploying Gerrit

Introduction

Gerrit is a powerful, web-based code review and project management tool for Git repositories. Developed by Google and used by major organizations like Android, Qt, and Eclipse, Gerrit has become the industry standard for collaborative software development and code review workflows.

Gerrit is renowned for its:

  • Advanced Code Review: Inline commenting, side-by-side diff viewing, and powerful review workflows
  • Git Integration: Deep integration with Git, supporting all Git operations seamlessly
  • Access Control: Fine-grained permissions system for repositories, branches, and even specific file paths
  • Change Management: Sophisticated change tracking with support for amendments, cherry-picks, and rebases
  • CI/CD Integration: Built-in hooks and API for integration with continuous integration systems
  • SSH and HTTP Access: Support for both SSH and HTTP(S) protocols for Git operations
  • Extensibility: Plugin system allowing customization and extension of functionality

Gerrit is particularly valuable for teams that need:

  • Mandatory code review before merging changes
  • Detailed audit trails of all code changes
  • Complex branching strategies and release management
  • Integration with existing build and test infrastructure

This comprehensive guide walks you through deploying Gerrit on Klutch.sh using Docker, including detailed installation steps, sample configurations, persistent storage setup, SSH access configuration, and production-ready best practices.

Prerequisites

Before you begin, ensure you have the following:

  • A Klutch.sh account
  • A GitHub account with a repository for your Gerrit project
  • Docker installed locally for testing (optional but recommended)
  • Basic understanding of Docker, Git, and code review workflows
  • An SSH client for accessing Gerrit via SSH (optional but recommended for full functionality)

Installation and Setup

Step 1: Create Your Project Directory

First, create a new directory for your Gerrit deployment project:

Terminal window
mkdir gerrit-klutch
cd gerrit-klutch
git init

Step 2: Create the Dockerfile

Create a Dockerfile in your project root directory. This Dockerfile will set up Gerrit with all necessary configurations:

FROM gerritcodereview/gerrit:3.9-ubuntu22
# Set the Gerrit site path
ENV GERRIT_SITE=/var/gerrit/review_site
# Create necessary directories
USER root
RUN mkdir -p ${GERRIT_SITE}/etc && \
mkdir -p ${GERRIT_SITE}/git && \
mkdir -p ${GERRIT_SITE}/index && \
mkdir -p ${GERRIT_SITE}/cache && \
mkdir -p ${GERRIT_SITE}/db && \
mkdir -p ${GERRIT_SITE}/logs && \
chown -R gerrit:gerrit ${GERRIT_SITE}
# Copy configuration files if they exist
# COPY gerrit.config ${GERRIT_SITE}/etc/gerrit.config
# COPY secure.config ${GERRIT_SITE}/etc/secure.config
# Switch back to gerrit user
USER gerrit
# Expose HTTP and SSH ports
EXPOSE 8080 29418
# Set working directory
WORKDIR ${GERRIT_SITE}
# Start Gerrit
ENTRYPOINT ["/var/gerrit/review_site/bin/gerrit.sh", "run"]

Note: This Dockerfile uses the official Gerrit image based on Ubuntu 22.04, which provides a stable and well-tested foundation for production deployments.

Step 3: Create Gerrit Configuration File

Create a gerrit.config file that will configure Gerrit’s basic settings. This file should be customized before deployment:

[gerrit]
basePath = git
canonicalWebUrl = https://gerrit.example-app.klutch.sh
serverId = gerrit-klutch-production
[container]
javaHome = /usr/lib/jvm/java-17-openjdk-amd64
javaOptions = -Xmx2048m
user = gerrit
[index]
type = lucene
[auth]
type = DEVELOPMENT_BECOME_ANY_ACCOUNT
# For production, change to LDAP, OAUTH, or another secure authentication method
[receive]
enableSignedPush = false
[sendemail]
smtpServer = localhost
# Configure SMTP settings for email notifications in production
[sshd]
listenAddress = *:29418
[httpd]
listenUrl = http://*:8080/
[cache]
directory = cache
[download]
command = checkout
command = cherry_pick
command = pull
command = format_patch
scheme = ssh
scheme = http
scheme = anon_http
scheme = anon_git

Important Configuration Notes:

  • canonicalWebUrl: Update this to your actual Klutch.sh URL
  • auth.type: The DEVELOPMENT_BECOME_ANY_ACCOUNT setting is for testing only. For production, configure proper authentication (LDAP, OAuth, OpenID, etc.)
  • javaOptions: Adjust memory settings based on your expected load and available resources
  • sendemail: Configure SMTP settings for email notifications in production environments

Step 4: Create a Secure Configuration File (Optional)

For production deployments, create a secure.config file to store sensitive information like database passwords and SMTP credentials:

[database]
# Add database credentials here if using external database
# username = gerrit
# password = your_secure_password
[sendemail]
# Add SMTP credentials here
# smtpUser = your_smtp_user
# smtpPass = your_smtp_password

Security Note: Never commit the secure.config file to your repository. Instead, create it during deployment or mount it as a secret.

Step 5: Create an Initialization Script

Create a init-gerrit.sh script to initialize Gerrit on first startup:

#!/bin/bash
set -e
GERRIT_SITE=/var/gerrit/review_site
# Check if Gerrit is already initialized
if [ ! -f "${GERRIT_SITE}/etc/gerrit.config" ]; then
echo "Initializing Gerrit for the first time..."
# Copy configuration files
cp /tmp/gerrit.config ${GERRIT_SITE}/etc/gerrit.config
# Initialize Gerrit
java -jar /var/gerrit/gerrit.war init \
--batch \
--site-path ${GERRIT_SITE} \
--no-auto-start
# Reindex for initial setup
java -jar /var/gerrit/gerrit.war reindex \
--site-path ${GERRIT_SITE}
echo "Gerrit initialization complete!"
else
echo "Gerrit is already initialized."
fi
# Start Gerrit
exec ${GERRIT_SITE}/bin/gerrit.sh run

Step 6: Update Your Dockerfile to Use Custom Configuration

If you want to include custom configuration files, update your Dockerfile:

FROM gerritcodereview/gerrit:3.9-ubuntu22
ENV GERRIT_SITE=/var/gerrit/review_site
USER root
# Create necessary directories
RUN mkdir -p ${GERRIT_SITE}/etc && \
mkdir -p ${GERRIT_SITE}/git && \
mkdir -p ${GERRIT_SITE}/index && \
mkdir -p ${GERRIT_SITE}/cache && \
mkdir -p ${GERRIT_SITE}/db && \
mkdir -p ${GERRIT_SITE}/logs
# Copy configuration files
COPY gerrit.config /tmp/gerrit.config
COPY init-gerrit.sh /usr/local/bin/init-gerrit.sh
# Set permissions
RUN chmod +x /usr/local/bin/init-gerrit.sh && \
chown -R gerrit:gerrit ${GERRIT_SITE}
USER gerrit
# Expose ports
EXPOSE 8080 29418
WORKDIR ${GERRIT_SITE}
# Use custom initialization script
ENTRYPOINT ["/usr/local/bin/init-gerrit.sh"]

Step 7: Test Locally (Optional)

Before deploying to Klutch.sh, test your Gerrit setup locally:

Terminal window
# Build the Docker image
docker build -t my-gerrit .
# Run the container with port mappings
docker run -d \
--name gerrit-test \
-p 8080:8080 \
-p 29418:29418 \
-v gerrit-data:/var/gerrit/review_site \
my-gerrit
# Check logs
docker logs -f gerrit-test
# Access Gerrit web interface
# Open http://localhost:8080 in your browser
# Test SSH connection
# ssh -p 29418 admin@localhost gerrit version
# Stop and remove the test container when done
docker stop gerrit-test
docker rm gerrit-test
docker volume rm gerrit-data

Step 8: Push to GitHub

Commit your Dockerfile and configuration files to your GitHub repository:

Terminal window
# Add files (but not secure.config if it contains secrets)
git add Dockerfile gerrit.config init-gerrit.sh
git commit -m "Add Gerrit deployment configuration"
git remote add origin https://github.com/yourusername/gerrit-klutch.git
git push -u origin main

Important: Add secure.config to your .gitignore file to prevent committing sensitive information:

Terminal window
echo "secure.config" >> .gitignore
git add .gitignore
git commit -m "Add secure.config to gitignore"
git push

Understanding Gerrit Ports

Gerrit uses two main ports for different purposes:

  • Port 8080 (HTTP): Web interface for code review, viewing changes, and administration
  • Port 29418 (SSH): Git operations, command-line access, and automation via SSH

When deploying on Klutch.sh:

  • HTTP traffic (port 8080) can use standard HTTP traffic type
  • SSH traffic (port 29418) requires TCP traffic type for full functionality

Deploying to Klutch.sh

Now that your Gerrit project is ready and pushed to GitHub, follow these comprehensive steps to deploy it on Klutch.sh with persistent storage and proper network configuration.

Deployment Steps

    1. Log in to Klutch.sh

      Navigate to klutch.sh/app and sign in to your account.

    2. Create a New Project

      Go to Create Project and give your project a meaningful name (e.g., “Gerrit Code Review”).

    3. Create a New App for HTTP Access

      Navigate to Create App and configure the following settings for the HTTP interface:

    4. Select Your Repository

      • Choose GitHub as your Git source
      • Select the repository containing your Dockerfile
      • Choose the branch you want to deploy (usually main or master)
    5. Configure HTTP Traffic

      • Traffic Type: Select HTTP (for the web interface)
      • Internal Port: Set to 8080 (the default Gerrit HTTP port)
    6. Set Environment Variables

      Add the following environment variables for your Gerrit configuration:

      • GERRIT_BASE_URL: The public URL for your Gerrit instance (e.g., https://gerrit.example-app.klutch.sh)
      • JAVA_OPTS: Java options for memory and performance (e.g., -Xmx2048m -Xms512m)
      • CANONICAL_WEB_URL: Same as GERRIT_BASE_URL for proper link generation

      Optional environment variables for production:

      • AUTH_TYPE: Authentication method (e.g., LDAP, OAUTH, OPENID)
      • SMTP_SERVER: SMTP server for email notifications
      • SMTP_USER: SMTP username
      • SMTP_PASS: SMTP password (mark as secret)
      • DATABASE_TYPE: If using external database (e.g., postgresql, mysql)
      • DATABASE_HOST: Database hostname
      • DATABASE_NAME: Database name
      • DATABASE_USER: Database username
      • DATABASE_PASSWORD: Database password (mark as secret)

      Security Note: Always mark sensitive values (passwords, API keys) as secrets in Klutch.sh.

    7. Attach Persistent Volumes

      Gerrit requires persistent storage for Git repositories, indexes, caches, and database files. Create and attach the following volumes:

      Primary Volume (Required):

      • Mount Path: /var/gerrit/review_site
      • Size: Choose based on expected repository size (minimum 10GB, recommended 50GB+ for production)

      This volume stores:

      • Git repositories (git/ directory)
      • Search indexes (index/ directory)
      • Cache files (cache/ directory)
      • Database files if using H2 (db/ directory)
      • Configuration files (etc/ directory)
      • Logs (logs/ directory)

      Important: All Gerrit data must persist between deployments, making this volume critical for data integrity.

    8. Configure Additional Settings

      • Region: Select the region closest to your development team for optimal latency
      • Compute Resources: Choose CPU and memory based on your team size
        • Small teams (< 10 developers): 1 CPU, 2GB RAM
        • Medium teams (10-50 developers): 2 CPU, 4GB RAM
        • Large teams (50+ developers): 4 CPU, 8GB RAM
      • Instances: Start with 1 instance (Gerrit’s architecture is typically single-instance)
    9. Deploy Your Gerrit Instance

      Click “Create” to start the deployment. Klutch.sh will:

      • Automatically detect your Dockerfile in the repository root
      • Build the Docker image with your custom configuration
      • Attach the persistent volume to preserve all data
      • Start your Gerrit container with proper networking
      • Assign a URL for web access
    10. Initial Setup and Configuration

      Once deployment is complete, you’ll receive a URL like https://gerrit.example-app.klutch.sh. Follow these steps to complete the setup:

      First-time access:

      • Navigate to your Gerrit URL in a web browser
      • The first user to access Gerrit will automatically become the administrator (if using DEVELOPMENT_BECOME_ANY_ACCOUNT auth)
      • For production authentication, configure your auth provider before first access

      Configure SSH access (if needed):

      • To enable SSH access for Git operations, you’ll need to create a second app with TCP traffic
      • See the “Configuring SSH Access” section below for detailed instructions
    11. Configure User Authentication (Production)

      For production deployments, update the authentication configuration:

      • Navigate to the Gerrit admin panel
      • Configure your authentication provider (LDAP, OAuth, OpenID, etc.)
      • Update the gerrit.config file in your repository with the authentication settings
      • Redeploy the application to apply changes

Configuring SSH Access for Git Operations

Gerrit’s full functionality requires SSH access for Git operations. To enable SSH access on Klutch.sh, you need to create a separate app with TCP traffic:

SSH Access Setup Steps

    1. Create a Second App for SSH Access

      In your Klutch.sh project, create another app from the same repository:

      • App name: gerrit-ssh (or similar descriptive name)
      • Same repository and branch as your HTTP app
    2. Configure TCP Traffic

      • Traffic Type: Select TCP (required for SSH connections)
      • Internal Port: Set to 29418 (Gerrit’s default SSH port)
    3. Attach the Same Persistent Volume

      Critical: Attach the same persistent volume used by the HTTP app:

      • Mount Path: /var/gerrit/review_site
      • Volume: Select the same volume as your HTTP app

      This ensures both apps share the same Git repositories and configuration.

    4. Use the Same Environment Variables

      Copy all environment variables from your HTTP app to maintain consistency.

    5. Deploy the SSH App

      Click “Create” to deploy. This app will handle SSH traffic on port 8000 (Klutch.sh’s external TCP port).

    6. Connect via SSH

      Users can now connect to Gerrit via SSH using port 8000:

      Terminal window
      # Add your SSH public key to Gerrit first (via web interface)
      # Then test the connection
      ssh -p 8000 username@gerrit-ssh.example-app.klutch.sh gerrit version
      # Clone a repository via SSH
      git clone ssh://username@gerrit-ssh.example-app.klutch.sh:8000/repository-name
    7. Configure Git Remote

      Update your Git configuration to use the SSH URL:

      Terminal window
      git remote add gerrit ssh://username@gerrit-ssh.example-app.klutch.sh:8000/your-repo

Important Notes:

  • Users must add their SSH public keys via the Gerrit web interface before using SSH
  • The SSH app and HTTP app must share the same persistent volume
  • Port 8000 is Klutch.sh’s external port for TCP traffic; internally it routes to port 29418

Setting Up Your First Project in Gerrit

After deployment, set up your first project:

Using the Web Interface

    1. Access Gerrit Admin

      • Navigate to your Gerrit URL
      • Sign in as an administrator
      • Go to BrowseRepositoriesCREATE NEW
    2. Create a Repository

      • Repository Name: my-project
      • Rights Inherit From: Leave as default or select a parent project
      • Create initial empty commit: Check this box (recommended)
      • Click CREATE
    3. Configure Project Access

      • Go to ProjectsList → Select your project → Access
      • Configure permissions for different user groups
      • Set up review requirements, submit rules, and branch permissions
    4. Add Users to Groups

      • Go to PeopleGroups
      • Create groups (e.g., Developers, Reviewers, Approvers)
      • Add users to appropriate groups
      • Grant group permissions in project access settings

Using SSH (Alternative)

Terminal window
# Create a new project via SSH
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit create-project my-project \
--empty-commit \
--description "My first project"
# List all projects
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit ls-projects
# Set project permissions
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit set-project my-project \
--submit-type REBASE_IF_NECESSARY

Using Gerrit for Code Review

Basic Workflow

  1. Clone the repository

    Terminal window
    git clone https://gerrit.example-app.klutch.sh/my-project
    cd my-project
  2. Install commit-msg hook

    Gerrit requires a special commit hook to add Change-Id to commits:

    Terminal window
    curl -Lo .git/hooks/commit-msg \
    https://gerrit.example-app.klutch.sh/tools/hooks/commit-msg
    chmod +x .git/hooks/commit-msg
  3. Make changes and commit

    Terminal window
    # Create a branch for your work
    git checkout -b feature/my-feature
    # Make your changes
    echo "My new feature" > feature.txt
    git add feature.txt
    # Commit with descriptive message
    git commit -m "Add my new feature" -m "This commit adds a new feature that does X, Y, and Z." -m "Bug: #1234"
  4. Push for review

    Terminal window
    # Push to refs/for/main (or your target branch)
    git push origin HEAD:refs/for/main
  5. Code review in web interface

    • Navigate to your Gerrit URL
    • Find your change in MyChanges
    • Reviewers can comment, vote, and approve
    • Make updates by amending your commit and pushing again
  6. Submit the change

    Once approved, click SUBMIT in the web interface to merge the change.


Environment Variables and Configuration

Core Environment Variables

VariableDescriptionExample ValueRequired
GERRIT_BASE_URLPublic URL of your Gerrit instancehttps://gerrit.example-app.klutch.shYes
CANONICAL_WEB_URLSame as GERRIT_BASE_URLhttps://gerrit.example-app.klutch.shYes
JAVA_OPTSJava memory and performance options-Xmx2048m -Xms512mRecommended

Nixpacks Runtime Variables

If you need to customize build or runtime behavior with Nixpacks, use these environment variables:

VariablePurposeExample
NIXPACKS_JDK_VERSIONSpecify Java version17
NIXPACKS_BUILD_CMDCustom build command./build.sh
NIXPACKS_START_CMDCustom start command/var/gerrit/review_site/bin/gerrit.sh run

Note: Since Gerrit uses a Dockerfile, Klutch.sh will automatically detect and use it. These Nixpacks variables are only relevant if you’re not using a Dockerfile.

Authentication Variables (Production)

For LDAP authentication:

VariableDescriptionExample
AUTH_TYPEAuthentication methodLDAP
LDAP_SERVERLDAP server URLldap://ldap.example.com
LDAP_ACCOUNT_BASELDAP search baseou=users,dc=example,dc=com
LDAP_GROUP_BASELDAP group search baseou=groups,dc=example,dc=com
LDAP_BIND_USERLDAP bind DNcn=admin,dc=example,dc=com
LDAP_BIND_PASSWORDLDAP bind passwordyour-password (mark as secret)

Email Notification Variables

VariableDescriptionExample
SMTP_SERVERSMTP server hostnamesmtp.gmail.com
SMTP_SERVER_PORTSMTP server port587
SMTP_USERSMTP usernameyour-email@gmail.com
SMTP_PASSSMTP passwordyour-app-password (mark as secret)
SMTP_FROMFrom email addressgerrit@example.com

Database Variables (External Database)

For PostgreSQL:

VariableDescriptionExample
DATABASE_TYPEDatabase typepostgresql
DATABASE_HOSTDatabase hostnamepostgres.example.com
DATABASE_PORTDatabase port5432
DATABASE_NAMEDatabase namegerrit
DATABASE_USERDatabase usernamegerrit_user
DATABASE_PASSWORDDatabase passwordsecure-password (mark as secret)

Persistent Storage Configuration

Understanding Gerrit’s Storage Structure

Gerrit stores all critical data under the GERRIT_SITE directory (default: /var/gerrit/review_site):

/var/gerrit/review_site/
├── bin/ # Gerrit executables and scripts
├── cache/ # Cache files (rebuilds automatically)
├── data/ # H2 database files (if using H2)
├── db/ # Database backup files
├── etc/ # Configuration files
│ ├── gerrit.config
│ ├── secure.config
│ └── replication.config
├── git/ # Git repositories (critical data)
├── index/ # Lucene search indexes
├── lib/ # Libraries and plugins
├── logs/ # Application logs
├── plugins/ # Installed plugins
└── static/ # Static web resources

Critical Directories Requiring Persistence

  • git/: Contains all Git repositories (CRITICAL - must persist)
  • db/ or data/: Database files (CRITICAL if using embedded H2)
  • etc/: Configuration files (CRITICAL)
  • index/: Search indexes (can rebuild, but recommended to persist)
  • cache/: Cache files (can rebuild, but persisting improves startup time)

Volume Configuration Best Practices

  1. Single Volume Approach (Recommended)

    Mount a single volume at /var/gerrit/review_site:

    • Pros: Simple configuration, ensures all data persists
    • Cons: Larger volume size required
    • Recommended Size: 50GB minimum, scale based on repository count
  2. Multiple Volume Approach (Advanced)

    Mount separate volumes for different directories:

    • /var/gerrit/review_site/git - Repository data
    • /var/gerrit/review_site/db - Database data
    • Pros: Fine-grained control, can optimize different storage types
    • Cons: More complex configuration
    • Note: Klutch.sh allows multiple volume mounts per app

Volume Sizing Guidelines

Team SizeRepositoriesRecommended Volume Size
Small (< 10 developers)< 10 repos20-50 GB
Medium (10-50 developers)10-50 repos50-200 GB
Large (50+ developers)50+ repos200GB-1TB+

Growth Factors to Consider:

  • Average repository size
  • Number of branches and tags per repository
  • Code review history retention
  • Backup and snapshot requirements
  • Search index size (approximately 10-15% of repository size)

Production Best Practices

Security Recommendations

  1. Authentication and Authorization

    • Never use DEVELOPMENT_BECOME_ANY_ACCOUNT in production
    • Configure proper authentication (LDAP, OAuth, OpenID Connect)
    • Implement role-based access control (RBAC)
    • Use strong passwords for all accounts
    • Enable two-factor authentication if supported by your auth provider
  2. Network Security

    • Use HTTPS for the web interface (Klutch.sh provides automatic TLS)
    • Use SSH key authentication instead of passwords
    • Restrict SSH access to known IP ranges if possible
    • Implement rate limiting for API access
  3. Data Security

    • Regular backups of the git/ directory and database
    • Encrypt sensitive configuration in secure.config
    • Store credentials as environment variables, not in code
    • Use Klutch.sh’s secret management for sensitive values
  4. SSH Key Management

    • Enforce key-based authentication
    • Regularly audit and rotate SSH keys
    • Remove SSH keys for departed team members immediately
    • Consider using SSH certificate authorities for large teams

Performance Optimization

  1. Java Memory Configuration

    Terminal window
    # Recommended JAVA_OPTS based on team size
    # Small team (< 10 developers)
    JAVA_OPTS="-Xmx1024m -Xms256m -XX:MaxMetaspaceSize=256m"
    # Medium team (10-50 developers)
    JAVA_OPTS="-Xmx2048m -Xms512m -XX:MaxMetaspaceSize=512m"
    # Large team (50+ developers)
    JAVA_OPTS="-Xmx4096m -Xms1024m -XX:MaxMetaspaceSize=1024m"
  2. Database Optimization

    • For production, use PostgreSQL or MySQL instead of H2
    • Configure connection pooling appropriately
    • Regular database maintenance (vacuum, optimize)
    • Monitor query performance and add indexes as needed
  3. Caching Strategy

    [cache]
    directory = cache
    [cache "web_sessions"]
    maxAge = 12 hours
    [cache "diff"]
    maxAge = 1 day
    [cache "diff_intraline"]
    maxAge = 1 day
  4. Search Index Optimization

    • Schedule regular reindexing during low-traffic periods
    • Monitor index size and performance
    • Consider using Elasticsearch for large installations (requires plugin)

Monitoring and Maintenance

  1. Key Metrics to Monitor

    • JVM memory usage and garbage collection
    • HTTP response times
    • SSH connection count and duration
    • Git operation performance (clone, fetch, push)
    • Repository count and total size
    • Active user count
    • Cache hit rates
  2. Log Management

    Terminal window
    # Key log files to monitor
    /var/gerrit/review_site/logs/error_log
    /var/gerrit/review_site/logs/httpd_log
    /var/gerrit/review_site/logs/sshd_log
    /var/gerrit/review_site/logs/gc_log
  3. Regular Maintenance Tasks

    • Weekly: Review error logs and performance metrics
    • Monthly: Backup repository data and database
    • Quarterly: Review and optimize database indexes
    • Annually: Clean up stale projects and user accounts

Backup Strategy

  1. What to Backup

    • Git repositories (git/ directory) - CRITICAL
    • Database (H2 files or external database dump)
    • Configuration files (etc/ directory)
    • SSH keys and user data
  2. Backup Methods

    Terminal window
    # Backup repositories (run on a schedule)
    tar -czf gerrit-repos-$(date +%Y%m%d).tar.gz \
    /var/gerrit/review_site/git/
    # Backup database (if using H2)
    tar -czf gerrit-db-$(date +%Y%m%d).tar.gz \
    /var/gerrit/review_site/db/
    # Backup configuration
    tar -czf gerrit-config-$(date +%Y%m%d).tar.gz \
    /var/gerrit/review_site/etc/
  3. Backup Frequency

    • Repositories: Daily incremental, weekly full backup
    • Database: Daily
    • Configuration: After every change

Scaling Considerations

  1. Vertical Scaling

    • Increase CPU for faster code review operations
    • Increase memory for larger repositories and more concurrent users
    • Increase storage as repositories grow
  2. Horizontal Scaling (Advanced)

    • Gerrit supports replication for read-only replicas
    • Use load balancers for multiple Gerrit instances
    • Separate primary (read-write) from replicas (read-only)
    • Configure replication in replication.config
  3. Database Scaling

    • Use managed PostgreSQL or MySQL services
    • Configure connection pooling
    • Implement read replicas for reporting queries

Integrating with CI/CD

Gerrit integrates seamlessly with continuous integration systems through hooks and API:

Jenkins Integration

  1. Install Gerrit Trigger Plugin in Jenkins

  2. Configure Gerrit connection in Jenkins:

    • Navigate to Manage JenkinsConfigure System
    • Add Gerrit Server configuration
    • Set SSH credentials for Jenkins user
  3. Create a Jenkins job triggered by Gerrit events:

    // Example Jenkinsfile for Gerrit
    pipeline {
    agent any
    stages {
    stage('Build') {
    steps {
    sh 'make build'
    }
    }
    stage('Test') {
    steps {
    sh 'make test'
    }
    }
    }
    post {
    success {
    // Post review with Verified +1
    sh '''
    ssh -p 8000 jenkins@gerrit-ssh.example-app.klutch.sh \
    gerrit review --verified +1 --message '"Build Successful"' ${GERRIT_PATCHSET_REVISION}
    '''
    }
    failure {
    // Post review with Verified -1
    sh '''
    ssh -p 8000 jenkins@gerrit-ssh.example-app.klutch.sh \
    gerrit review --verified -1 --message '"Build Failed"' ${GERRIT_PATCHSET_REVISION}
    '''
    }
    }
    }

Git Mirroring to External Systems

While Gerrit is the primary review system, you can mirror repositories to external Git hosting services using Gerrit’s built-in replication plugin or custom hooks.

Using Gerrit’s replication plugin:

Configure replication in your replication.config file:

[remote "external-mirror"]
url = git@external-host.com:org/${name}.git
push = +refs/heads/*:refs/heads/*
push = +refs/tags/*:refs/tags/*
threads = 3

Using Git post-receive hooks:

Create a custom hook script that pushes to external repositories after changes are merged.

API Integration

Use Gerrit’s REST API for custom integrations:

Terminal window
# Get change details
curl -X GET https://gerrit.example-app.klutch.sh/changes/12345
# Post a review
curl -X POST https://gerrit.example-app.klutch.sh/changes/12345/revisions/current/review \
-H "Content-Type: application/json" \
-d '{"labels":{"Code-Review":+1},"message":"LGTM"}'
# Submit a change
curl -X POST https://gerrit.example-app.klutch.sh/changes/12345/submit

Troubleshooting

Common Issues and Solutions

Cannot Access Gerrit Web Interface

Symptoms: Browser shows connection refused or timeout

Solutions:

  • Verify the HTTP app is running in Klutch.sh dashboard
  • Check the internal port is set to 8080
  • Review container logs for startup errors
  • Ensure environment variables are correctly set

SSH Connection Fails

Symptoms: ssh: connect to host gerrit-ssh.example-app.klutch.sh port 8000: Connection refused

Solutions:

  • Verify the SSH/TCP app is running
  • Confirm traffic type is set to TCP (not HTTP)
  • Check internal port is set to 29418
  • Ensure both apps share the same persistent volume
  • Verify SSH public key is added in Gerrit web interface

Gerrit Fails to Start

Symptoms: Container keeps restarting

Solutions:

  • Check container logs:
    Terminal window
    # View logs in Klutch.sh dashboard or use Docker
    docker logs <container-id>
  • Common causes:
    • Insufficient memory (increase JAVA_OPTS or container memory)
    • Corrupted database (restore from backup)
    • Invalid configuration (check gerrit.config syntax)
    • Permission issues on volumes (ensure proper ownership)

Data Loss After Redeployment

Symptoms: Repositories or changes disappear after deployment

Solutions:

  • Verify persistent volume is attached at /var/gerrit/review_site
  • Check volume has sufficient space
  • Ensure volume wasn’t accidentally deleted or recreated
  • Restore from backup if necessary

Poor Performance

Symptoms: Slow web interface, timeouts, high CPU usage

Solutions:

  • Increase memory allocation:
    Terminal window
    JAVA_OPTS="-Xmx4096m -Xms1024m"
  • Check disk I/O (volume performance)
  • Reindex search indexes:
    Terminal window
    java -jar /var/gerrit/gerrit.war reindex \
    --site-path /var/gerrit/review_site
  • Review and optimize database queries
  • Consider upgrading compute resources

Email Notifications Not Working

Symptoms: Users don’t receive email notifications

Solutions:

  • Verify SMTP configuration in environment variables
  • Check SMTP credentials are correct
  • Test SMTP connection:
    Terminal window
    # Test from container
    telnet smtp.gmail.com 587
  • Review email logs in /var/gerrit/review_site/logs/
  • Ensure firewall allows outbound SMTP traffic

Authentication Issues

Symptoms: Cannot log in, authentication errors

Solutions:

  • For development: Verify AUTH_TYPE=DEVELOPMENT_BECOME_ANY_ACCOUNT
  • For LDAP: Check LDAP_SERVER and credentials
  • For OAuth: Verify OAuth provider configuration
  • Review authentication logs
  • Clear browser cookies and cache

Debug Commands

Useful commands for troubleshooting:

Terminal window
# Check Gerrit version
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit version
# Show system status
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit show-status
# List all plugins
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit plugin ls
# Reload configuration without restart
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit reload-config
# Flush caches
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit flush-caches
# Show active connections
ssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit show-connections

Getting Help

If you continue to experience issues:

  1. Review Gerrit logs thoroughly
  2. Check Klutch.sh documentation
  3. Consult official Gerrit documentation
  4. Search or post in Gerrit community forums

Advanced Configuration

Custom Plugins

Gerrit supports plugins for extended functionality:

  1. Download plugins from Gerrit CI

  2. Add to Dockerfile:

    # Download and install plugins
    RUN wget -P /var/gerrit/review_site/plugins/ \
    https://gerrit-ci.gerritforge.com/view/Plugins-stable-3.9/job/plugin-avatars-external-bazel-stable-3.9/lastSuccessfulBuild/artifact/bazel-bin/plugins/avatars-external/avatars-external.jar
  3. Popular plugins:

    • avatars-external: Display user avatars from external sources
    • delete-project: Allow project deletion
    • download-commands: Additional download command options
    • webhooks: Send webhooks on Gerrit events
    • replication: Replicate repositories to remote locations

Replication Configuration

For disaster recovery or geographic distribution:

Create replication.config:

[remote "github-backup"]
url = git@github.com:yourorg/${name}.git
push = +refs/heads/*:refs/heads/*
push = +refs/tags/*:refs/tags/*
threads = 3
authGroup = Replication

Custom Themes

Customize Gerrit’s appearance:

# Add custom theme
COPY GerritSite.css /var/gerrit/review_site/etc/
COPY GerritSiteHeader.html /var/gerrit/review_site/etc/

Multi-Primary Setup (Advanced)

For high availability with multiple primary nodes:

  • Requires external database (PostgreSQL or MySQL)
  • Shared file system or object storage for Git repositories
  • Load balancer configuration
  • Coordination for cache invalidation

This is an advanced setup and requires careful planning.


Migration from Other Systems

Migrating from GitLab

  1. Export GitLab repositories as bare Git repos

  2. Import into Gerrit:

    Terminal window
    # For each repository
    git clone --bare https://gitlab.com/yourorg/repo.git
    cd repo.git
    git push --mirror ssh://admin@gerrit-ssh.example-app.klutch.sh:8000/repo
  3. Migrate users and permissions manually through Gerrit UI

Migrating from Bitbucket

Similar process to GitLab:

Terminal window
git clone --bare https://bitbucket.org/yourorg/repo.git
cd repo.git
git push --mirror ssh://admin@gerrit-ssh.example-app.klutch.sh:8000/repo

Migrating from Self-hosted Git

  1. Prepare repositories:

    Terminal window
    cd /path/to/repos
    for repo in *.git; do
    cd $repo
    git push --mirror ssh://admin@gerrit-ssh.example-app.klutch.sh:8000/${repo%.git}
    cd ..
    done
  2. Import users: Create CSV file and use Gerrit admin tools


Additional Resources


Conclusion

Deploying Gerrit on Klutch.sh provides a robust, scalable code review platform for your development team. By following this comprehensive guide, you’ve set up a production-ready Gerrit instance with:

  • Persistent storage for all Git repositories and configuration
  • Secure authentication and access control
  • HTTP access for web-based code review
  • Optional SSH access for Git operations
  • Integration capabilities with CI/CD systems
  • Performance optimization for teams of all sizes

Your Gerrit instance is now ready to streamline your code review process, improve code quality, and enhance collaboration across your development team. As your team grows, you can scale your Gerrit deployment by adjusting compute resources, optimizing configuration, and implementing advanced features like replication and custom plugins.

Remember to regularly backup your data, monitor performance metrics, and keep your Gerrit installation updated with the latest security patches and features. Happy code reviewing!