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:
mkdir gerrit-klutchcd gerrit-klutchgit initStep 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 pathENV GERRIT_SITE=/var/gerrit/review_site
# Create necessary directoriesUSER rootRUN 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 userUSER gerrit
# Expose HTTP and SSH portsEXPOSE 8080 29418
# Set working directoryWORKDIR ${GERRIT_SITE}
# Start GerritENTRYPOINT ["/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_gitImportant Configuration Notes:
- canonicalWebUrl: Update this to your actual Klutch.sh URL
- auth.type: The
DEVELOPMENT_BECOME_ANY_ACCOUNTsetting 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_passwordSecurity 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/bashset -e
GERRIT_SITE=/var/gerrit/review_site
# Check if Gerrit is already initializedif [ ! -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 Gerritexec ${GERRIT_SITE}/bin/gerrit.sh runStep 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 directoriesRUN 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 filesCOPY gerrit.config /tmp/gerrit.configCOPY init-gerrit.sh /usr/local/bin/init-gerrit.sh
# Set permissionsRUN chmod +x /usr/local/bin/init-gerrit.sh && \ chown -R gerrit:gerrit ${GERRIT_SITE}
USER gerrit
# Expose portsEXPOSE 8080 29418
WORKDIR ${GERRIT_SITE}
# Use custom initialization scriptENTRYPOINT ["/usr/local/bin/init-gerrit.sh"]Step 7: Test Locally (Optional)
Before deploying to Klutch.sh, test your Gerrit setup locally:
# Build the Docker imagedocker build -t my-gerrit .
# Run the container with port mappingsdocker run -d \ --name gerrit-test \ -p 8080:8080 \ -p 29418:29418 \ -v gerrit-data:/var/gerrit/review_site \ my-gerrit
# Check logsdocker 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 donedocker stop gerrit-testdocker rm gerrit-testdocker volume rm gerrit-dataStep 8: Push to GitHub
Commit your Dockerfile and configuration files to your GitHub repository:
# Add files (but not secure.config if it contains secrets)git add Dockerfile gerrit.config init-gerrit.shgit commit -m "Add Gerrit deployment configuration"git remote add origin https://github.com/yourusername/gerrit-klutch.gitgit push -u origin mainImportant: Add secure.config to your .gitignore file to prevent committing sensitive information:
echo "secure.config" >> .gitignoregit add .gitignoregit commit -m "Add secure.config to gitignore"git pushUnderstanding 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
-
Log in to Klutch.sh
Navigate to klutch.sh/app and sign in to your account.
-
Create a New Project
Go to Create Project and give your project a meaningful name (e.g., “Gerrit Code Review”).
-
Create a New App for HTTP Access
Navigate to Create App and configure the following settings for the HTTP interface:
-
Select Your Repository
- Choose GitHub as your Git source
- Select the repository containing your Dockerfile
- Choose the branch you want to deploy (usually
mainormaster)
-
Configure HTTP Traffic
- Traffic Type: Select HTTP (for the web interface)
- Internal Port: Set to
8080(the default Gerrit HTTP port)
-
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 notificationsSMTP_USER: SMTP usernameSMTP_PASS: SMTP password (mark as secret)DATABASE_TYPE: If using external database (e.g.,postgresql,mysql)DATABASE_HOST: Database hostnameDATABASE_NAME: Database nameDATABASE_USER: Database usernameDATABASE_PASSWORD: Database password (mark as secret)
Security Note: Always mark sensitive values (passwords, API keys) as secrets in Klutch.sh.
-
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.
- Mount Path:
-
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)
-
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
-
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
-
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.configfile 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
-
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
- App name:
-
Configure TCP Traffic
- Traffic Type: Select TCP (required for SSH connections)
- Internal Port: Set to
29418(Gerrit’s default SSH port)
-
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.
- Mount Path:
-
Use the Same Environment Variables
Copy all environment variables from your HTTP app to maintain consistency.
-
Deploy the SSH App
Click “Create” to deploy. This app will handle SSH traffic on port 8000 (Klutch.sh’s external TCP port).
-
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 connectionssh -p 8000 username@gerrit-ssh.example-app.klutch.sh gerrit version# Clone a repository via SSHgit clone ssh://username@gerrit-ssh.example-app.klutch.sh:8000/repository-name -
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
-
Access Gerrit Admin
- Navigate to your Gerrit URL
- Sign in as an administrator
- Go to Browse → Repositories → CREATE NEW
-
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
- Repository Name:
-
Configure Project Access
- Go to Projects → List → Select your project → Access
- Configure permissions for different user groups
- Set up review requirements, submit rules, and branch permissions
-
Add Users to Groups
- Go to People → Groups
- Create groups (e.g.,
Developers,Reviewers,Approvers) - Add users to appropriate groups
- Grant group permissions in project access settings
Using SSH (Alternative)
# Create a new project via SSHssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit create-project my-project \ --empty-commit \ --description "My first project"
# List all projectsssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit ls-projects
# Set project permissionsssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit set-project my-project \ --submit-type REBASE_IF_NECESSARYUsing Gerrit for Code Review
Basic Workflow
-
Clone the repository
Terminal window git clone https://gerrit.example-app.klutch.sh/my-projectcd my-project -
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-msgchmod +x .git/hooks/commit-msg -
Make changes and commit
Terminal window # Create a branch for your workgit checkout -b feature/my-feature# Make your changesecho "My new feature" > feature.txtgit add feature.txt# Commit with descriptive messagegit commit -m "Add my new feature" -m "This commit adds a new feature that does X, Y, and Z." -m "Bug: #1234" -
Push for review
Terminal window # Push to refs/for/main (or your target branch)git push origin HEAD:refs/for/main -
Code review in web interface
- Navigate to your Gerrit URL
- Find your change in My → Changes
- Reviewers can comment, vote, and approve
- Make updates by amending your commit and pushing again
-
Submit the change
Once approved, click SUBMIT in the web interface to merge the change.
Environment Variables and Configuration
Core Environment Variables
| Variable | Description | Example Value | Required |
|---|---|---|---|
GERRIT_BASE_URL | Public URL of your Gerrit instance | https://gerrit.example-app.klutch.sh | Yes |
CANONICAL_WEB_URL | Same as GERRIT_BASE_URL | https://gerrit.example-app.klutch.sh | Yes |
JAVA_OPTS | Java memory and performance options | -Xmx2048m -Xms512m | Recommended |
Nixpacks Runtime Variables
If you need to customize build or runtime behavior with Nixpacks, use these environment variables:
| Variable | Purpose | Example |
|---|---|---|
NIXPACKS_JDK_VERSION | Specify Java version | 17 |
NIXPACKS_BUILD_CMD | Custom build command | ./build.sh |
NIXPACKS_START_CMD | Custom 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:
| Variable | Description | Example |
|---|---|---|
AUTH_TYPE | Authentication method | LDAP |
LDAP_SERVER | LDAP server URL | ldap://ldap.example.com |
LDAP_ACCOUNT_BASE | LDAP search base | ou=users,dc=example,dc=com |
LDAP_GROUP_BASE | LDAP group search base | ou=groups,dc=example,dc=com |
LDAP_BIND_USER | LDAP bind DN | cn=admin,dc=example,dc=com |
LDAP_BIND_PASSWORD | LDAP bind password | your-password (mark as secret) |
Email Notification Variables
| Variable | Description | Example |
|---|---|---|
SMTP_SERVER | SMTP server hostname | smtp.gmail.com |
SMTP_SERVER_PORT | SMTP server port | 587 |
SMTP_USER | SMTP username | your-email@gmail.com |
SMTP_PASS | SMTP password | your-app-password (mark as secret) |
SMTP_FROM | From email address | gerrit@example.com |
Database Variables (External Database)
For PostgreSQL:
| Variable | Description | Example |
|---|---|---|
DATABASE_TYPE | Database type | postgresql |
DATABASE_HOST | Database hostname | postgres.example.com |
DATABASE_PORT | Database port | 5432 |
DATABASE_NAME | Database name | gerrit |
DATABASE_USER | Database username | gerrit_user |
DATABASE_PASSWORD | Database password | secure-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 resourcesCritical Directories Requiring Persistence
git/: Contains all Git repositories (CRITICAL - must persist)db/ordata/: 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
-
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
-
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 Size | Repositories | Recommended Volume Size |
|---|---|---|
| Small (< 10 developers) | < 10 repos | 20-50 GB |
| Medium (10-50 developers) | 10-50 repos | 50-200 GB |
| Large (50+ developers) | 50+ repos | 200GB-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
-
Authentication and Authorization
- Never use
DEVELOPMENT_BECOME_ANY_ACCOUNTin 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
- Never use
-
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
-
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
- Regular backups of the
-
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
-
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" -
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
-
Caching Strategy
[cache]directory = cache[cache "web_sessions"]maxAge = 12 hours[cache "diff"]maxAge = 1 day[cache "diff_intraline"]maxAge = 1 day -
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
-
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
-
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 -
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
-
What to Backup
- Git repositories (
git/directory) - CRITICAL - Database (H2 files or external database dump)
- Configuration files (
etc/directory) - SSH keys and user data
- Git repositories (
-
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 configurationtar -czf gerrit-config-$(date +%Y%m%d).tar.gz \/var/gerrit/review_site/etc/ -
Backup Frequency
- Repositories: Daily incremental, weekly full backup
- Database: Daily
- Configuration: After every change
Scaling Considerations
-
Vertical Scaling
- Increase CPU for faster code review operations
- Increase memory for larger repositories and more concurrent users
- Increase storage as repositories grow
-
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
-
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
-
Install Gerrit Trigger Plugin in Jenkins
-
Configure Gerrit connection in Jenkins:
- Navigate to Manage Jenkins → Configure System
- Add Gerrit Server configuration
- Set SSH credentials for Jenkins user
-
Create a Jenkins job triggered by Gerrit events:
// Example Jenkinsfile for Gerritpipeline {agent anystages {stage('Build') {steps {sh 'make build'}}stage('Test') {steps {sh 'make test'}}}post {success {// Post review with Verified +1sh '''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 -1sh '''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 = 3Using 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:
# Get change detailscurl -X GET https://gerrit.example-app.klutch.sh/changes/12345
# Post a reviewcurl -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 changecurl -X POST https://gerrit.example-app.klutch.sh/changes/12345/submitTroubleshooting
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 Dockerdocker logs <container-id> - Common causes:
- Insufficient memory (increase JAVA_OPTS or container memory)
- Corrupted database (restore from backup)
- Invalid configuration (check
gerrit.configsyntax) - 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 containertelnet 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:
# Check Gerrit versionssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit version
# Show system statusssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit show-status
# List all pluginsssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit plugin ls
# Reload configuration without restartssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit reload-config
# Flush cachesssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit flush-caches
# Show active connectionsssh -p 8000 admin@gerrit-ssh.example-app.klutch.sh gerrit show-connectionsGetting Help
If you continue to experience issues:
- Review Gerrit logs thoroughly
- Check Klutch.sh documentation
- Consult official Gerrit documentation
- Search or post in Gerrit community forums
Advanced Configuration
Custom Plugins
Gerrit supports plugins for extended functionality:
-
Download plugins from Gerrit CI
-
Add to Dockerfile:
# Download and install pluginsRUN 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 -
Popular plugins:
avatars-external: Display user avatars from external sourcesdelete-project: Allow project deletiondownload-commands: Additional download command optionswebhooks: Send webhooks on Gerrit eventsreplication: 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 = ReplicationCustom Themes
Customize Gerrit’s appearance:
# Add custom themeCOPY 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
-
Export GitLab repositories as bare Git repos
-
Import into Gerrit:
Terminal window # For each repositorygit clone --bare https://gitlab.com/yourorg/repo.gitcd repo.gitgit push --mirror ssh://admin@gerrit-ssh.example-app.klutch.sh:8000/repo -
Migrate users and permissions manually through Gerrit UI
Migrating from Bitbucket
Similar process to GitLab:
git clone --bare https://bitbucket.org/yourorg/repo.gitcd repo.gitgit push --mirror ssh://admin@gerrit-ssh.example-app.klutch.sh:8000/repoMigrating from Self-hosted Git
-
Prepare repositories:
Terminal window cd /path/to/reposfor repo in *.git; docd $repogit push --mirror ssh://admin@gerrit-ssh.example-app.klutch.sh:8000/${repo%.git}cd ..done -
Import users: Create CSV file and use Gerrit admin tools
Additional Resources
- Klutch.sh Documentation
- Official Gerrit Documentation
- Gerrit Docker Image Documentation
- Klutch.sh Volumes Guide
- Klutch.sh Networking Guide
- Gerrit Configuration Documentation
- Gerrit Community Discussion Group
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!