How to set up GitLab on Linux
How to Set Up GitLab on Linux: A Comprehensive Installation Guide
GitLab has become one of the most popular DevOps platforms, offering a complete solution for source code management, continuous integration, and deployment pipelines. Setting up GitLab on your Linux server provides you with full control over your development workflow, enhanced security, and the ability to customize your environment according to your organization's needs.
This comprehensive guide will walk you through the entire process of installing and configuring GitLab on Linux, from initial system preparation to advanced configuration options. Whether you're a system administrator looking to deploy GitLab for your team or a developer wanting to understand the setup process, this article covers everything you need to know.
Table of Contents
1. [Prerequisites and System Requirements](#prerequisites-and-system-requirements)
2. [Choosing Your Installation Method](#choosing-your-installation-method)
3. [Pre-Installation System Preparation](#pre-installation-system-preparation)
4. [Installing GitLab Community Edition](#installing-gitlab-community-edition)
5. [Initial Configuration](#initial-configuration)
6. [SSL/TLS Configuration](#ssltls-configuration)
7. [Email Configuration](#email-configuration)
8. [Backup Configuration](#backup-configuration)
9. [Performance Optimization](#performance-optimization)
10. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting)
11. [Best Practices and Security Hardening](#best-practices-and-security-hardening)
12. [Maintenance and Updates](#maintenance-and-updates)
Prerequisites and System Requirements
Before installing GitLab on your Linux system, it's essential to ensure your server meets the minimum requirements and has the necessary dependencies installed.
Hardware Requirements
GitLab's resource requirements depend on the number of users and repositories you plan to support:
Minimum Requirements (up to 500 users):
- CPU: 4 cores
- Memory: 4GB RAM
- Storage: 10GB available space (plus space for repositories)
Recommended Requirements (500+ users):
- CPU: 8+ cores
- Memory: 8GB+ RAM
- Storage: 50GB+ available space with SSD recommended
Supported Linux Distributions
GitLab officially supports the following Linux distributions:
- Ubuntu 18.04, 20.04, 22.04 LTS
- Debian 9, 10, 11
- CentOS 7, 8
- Red Hat Enterprise Linux 7, 8, 9
- SUSE Linux Enterprise Server 12, 15
- Amazon Linux 2
Network Requirements
Ensure your server has:
- A static IP address or proper DNS configuration
- Open ports: 80 (HTTP), 443 (HTTPS), 22 (SSH)
- Reliable internet connection for package downloads
Choosing Your Installation Method
GitLab offers several installation methods, each with its own advantages:
1. Omnibus Package Installation (Recommended)
The Omnibus package is the easiest and most popular installation method. It includes all necessary components and handles configuration automatically.
Advantages:
- Simple installation process
- Automatic dependency management
- Built-in backup and restore tools
- Easy updates and maintenance
2. Docker Installation
Docker installation provides containerized deployment with easy scalability.
Advantages:
- Isolated environment
- Easy to scale and replicate
- Simplified backup and migration
3. Source Installation
Installing from source gives you maximum control but requires more technical expertise.
Advantages:
- Full customization control
- Latest features and updates
- Minimal resource overhead
For this guide, we'll focus on the Omnibus package installation as it's the most straightforward and widely used method.
Pre-Installation System Preparation
Step 1: Update Your System
First, ensure your Linux system is up to date:
```bash
For Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
For CentOS/RHEL
sudo yum update -y
or for newer versions
sudo dnf update -y
```
Step 2: Install Required Dependencies
Install essential packages that GitLab requires:
```bash
For Ubuntu/Debian
sudo apt install -y curl openssh-server ca-certificates tzdata perl
For CentOS/RHEL
sudo yum install -y curl policycoreutils openssh-server openssh-clients
sudo systemctl enable sshd
sudo systemctl start sshd
```
Step 3: Configure Firewall
Configure your firewall to allow HTTP, HTTPS, and SSH traffic:
```bash
For Ubuntu/Debian (using ufw)
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable
For CentOS/RHEL (using firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
```
Step 4: Install and Configure Postfix (Optional)
If you want GitLab to send notification emails, install Postfix:
```bash
For Ubuntu/Debian
sudo apt install -y postfix
For CentOS/RHEL
sudo yum install -y postfix
sudo systemctl enable postfix
sudo systemctl start postfix
```
During Postfix installation, select "Internet Site" and use your server's external FQDN.
Installing GitLab Community Edition
Step 1: Add GitLab Repository
Add the official GitLab repository to your system:
```bash
Download and run the repository setup script
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
For CentOS/RHEL
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
```
Step 2: Install GitLab Package
Install GitLab Community Edition:
```bash
For Ubuntu/Debian
sudo EXTERNAL_URL="http://your-domain.com" apt install -y gitlab-ce
For CentOS/RHEL
sudo EXTERNAL_URL="http://your-domain.com" yum install -y gitlab-ce
```
Replace `your-domain.com` with your actual domain name or server IP address.
Step 3: Verify Installation
After installation completes, GitLab should be accessible via your web browser. The installation process will display the initial root password location:
```bash
View the initial root password
sudo cat /etc/gitlab/initial_root_password
```
Important: Save this password immediately, as the file will be automatically deleted after 24 hours.
Initial Configuration
Step 1: Access GitLab Web Interface
Open your web browser and navigate to your GitLab URL. You'll see the GitLab login page.
- Username: `root`
- Password: Use the password from `/etc/gitlab/initial_root_password`
Step 2: Change Root Password
Immediately after logging in:
1. Click on your avatar in the top-right corner
2. Select "Edit profile"
3. Click "Password" in the left sidebar
4. Enter your current password and set a new, strong password
5. Click "Save password"
Step 3: Configure Basic Settings
Navigate to Admin Area > Settings > General to configure:
- Sign-up restrictions: Disable public sign-ups if not needed
- Account and limit settings: Set user limits and project restrictions
- Sign-in restrictions: Configure password requirements and session duration
SSL/TLS Configuration
Securing your GitLab installation with SSL/TLS is crucial for production environments.
Method 1: Using Let's Encrypt (Recommended)
GitLab can automatically obtain and renew Let's Encrypt certificates:
```bash
Edit GitLab configuration
sudo nano /etc/gitlab/gitlab.rb
```
Add or modify these lines:
```ruby
external_url 'https://your-domain.com'
letsencrypt['enable'] = true
letsencrypt['contact_emails'] = ['admin@your-domain.com']
letsencrypt['auto_renew'] = true
```
Reconfigure GitLab:
```bash
sudo gitlab-ctl reconfigure
```
Method 2: Using Custom SSL Certificates
If you have your own SSL certificates:
```bash
Create SSL directory
sudo mkdir -p /etc/gitlab/ssl
sudo chmod 755 /etc/gitlab/ssl
Copy your certificates
sudo cp your-domain.com.crt /etc/gitlab/ssl/
sudo cp your-domain.com.key /etc/gitlab/ssl/
sudo chmod 600 /etc/gitlab/ssl/your-domain.com.*
```
Update GitLab configuration:
```ruby
external_url 'https://your-domain.com'
nginx['ssl_certificate'] = "/etc/gitlab/ssl/your-domain.com.crt"
nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/your-domain.com.key"
```
Reconfigure GitLab:
```bash
sudo gitlab-ctl reconfigure
```
Email Configuration
Configure GitLab to send notification emails:
SMTP Configuration
Edit the GitLab configuration file:
```bash
sudo nano /etc/gitlab/gitlab.rb
```
Add SMTP settings (example for Gmail):
```ruby
gitlab_rails['smtp_enable'] = true
gitlab_rails['smtp_address'] = "smtp.gmail.com"
gitlab_rails['smtp_port'] = 587
gitlab_rails['smtp_user_name'] = "your-email@gmail.com"
gitlab_rails['smtp_password'] = "your-app-password"
gitlab_rails['smtp_domain'] = "smtp.gmail.com"
gitlab_rails['smtp_authentication'] = "login"
gitlab_rails['smtp_enable_starttls_auto'] = true
gitlab_rails['smtp_tls'] = false
Set the email address for GitLab
gitlab_rails['gitlab_email_from'] = 'gitlab@your-domain.com'
gitlab_rails['gitlab_email_display_name'] = 'GitLab'
```
Reconfigure and test:
```bash
sudo gitlab-ctl reconfigure
sudo gitlab-rails console
```
In the Rails console, test email sending:
```ruby
Notify.test_email('test@example.com', 'Test Subject', 'Test Body').deliver_now
```
Backup Configuration
Regular backups are essential for data protection:
Configure Automatic Backups
Edit GitLab configuration:
```ruby
Backup settings
gitlab_rails['backup_path'] = "/var/opt/gitlab/backups"
gitlab_rails['backup_keep_time'] = 604800 # 7 days
gitlab_rails['backup_upload_connection'] = {
'provider' => 'AWS',
'region' => 'us-east-1',
'aws_access_key_id' => 'your-access-key',
'aws_secret_access_key' => 'your-secret-key'
}
gitlab_rails['backup_upload_remote_directory'] = 'your-s3-bucket'
```
Create Backup Script
Create a backup script:
```bash
sudo nano /opt/gitlab-backup.sh
```
```bash
#!/bin/bash
GitLab backup script
Create backup
gitlab-backup create STRATEGY=copy
Backup configuration files
tar czf /var/opt/gitlab/backups/$(date +%s)_gitlab_config_backup.tar.gz -C / etc/gitlab/gitlab.rb etc/gitlab/gitlab-secrets.json
Clean old backups (keep last 7 days)
find /var/opt/gitlab/backups -name "*.tar" -mtime +7 -delete
```
Make it executable and add to crontab:
```bash
sudo chmod +x /opt/gitlab-backup.sh
Add to crontab for daily backups at 2 AM
sudo crontab -e
0 2 * /opt/gitlab-backup.sh
```
Performance Optimization
Database Optimization
Configure PostgreSQL for better performance:
```ruby
PostgreSQL settings
postgresql['shared_buffers'] = "256MB"
postgresql['effective_cache_size'] = "1GB"
postgresql['work_mem'] = "16MB"
postgresql['maintenance_work_mem'] = "64MB"
postgresql['checkpoint_completion_target'] = 0.9
postgresql['wal_buffers'] = "16MB"
postgresql['default_statistics_target'] = 100
```
Redis Configuration
Optimize Redis for GitLab:
```ruby
Redis settings
redis['maxmemory'] = "256mb"
redis['maxmemory_policy'] = "allkeys-lru"
redis['save'] = []
```
Unicorn/Puma Configuration
Adjust application server settings:
```ruby
Puma settings (GitLab 13.0+)
puma['worker_processes'] = 4
puma['min_threads'] = 4
puma['max_threads'] = 4
puma['worker_timeout'] = 60
```
Enable Monitoring
Enable built-in monitoring:
```ruby
Monitoring settings
prometheus_monitoring['enable'] = true
grafana['enable'] = true
```
Common Issues and Troubleshooting
Issue 1: GitLab Not Starting
Symptoms: GitLab services fail to start after installation or configuration changes.
Solutions:
```bash
Check GitLab status
sudo gitlab-ctl status
View logs
sudo gitlab-ctl tail
Restart all services
sudo gitlab-ctl restart
Reconfigure GitLab
sudo gitlab-ctl reconfigure
```
Issue 2: 502 Bad Gateway Error
Symptoms: Browser shows "502 Bad Gateway" when accessing GitLab.
Solutions:
```bash
Check if all services are running
sudo gitlab-ctl status
Restart Unicorn/Puma
sudo gitlab-ctl restart puma
Check system resources
free -h
df -h
```
Issue 3: SSL Certificate Issues
Symptoms: SSL certificate errors or warnings in browser.
Solutions:
```bash
Check certificate validity
sudo gitlab-ctl status nginx
Renew Let's Encrypt certificate
sudo gitlab-ctl renew-le-certs
Check certificate files
sudo ls -la /etc/gitlab/ssl/
```
Issue 4: High Memory Usage
Symptoms: Server running out of memory, slow performance.
Solutions:
```bash
Reduce worker processes
Edit /etc/gitlab/gitlab.rb
puma['worker_processes'] = 2
Reduce database connections
postgresql['max_connections'] = 100
Reconfigure
sudo gitlab-ctl reconfigure
```
Issue 5: Database Connection Errors
Symptoms: GitLab cannot connect to PostgreSQL database.
Solutions:
```bash
Check PostgreSQL status
sudo gitlab-ctl status postgresql
Restart PostgreSQL
sudo gitlab-ctl restart postgresql
Check database logs
sudo gitlab-ctl tail postgresql
```
Best Practices and Security Hardening
Security Configuration
1. Disable Unused Features
```ruby
Disable features you don't need
gitlab_rails['gravatar_enabled'] = false
gitlab_rails['usage_ping_enabled'] = false
pages_enabled = false
```
2. Configure Rate Limiting
```ruby
Rate limiting
gitlab_rails['rack_attack_git_basic_auth'] = {
'enabled' => true,
'ip_whitelist' => ["127.0.0.1"],
'maxretry' => 10,
'findtime' => 60,
'bantime' => 3600
}
```
3. Enable Two-Factor Authentication
Force 2FA for all users:
1. Go to Admin Area > Settings > General
2. Expand Sign-in restrictions
3. Enable "Require two-factor authentication"
4. Configure SSH Key Restrictions
```ruby
SSH key restrictions
gitlab_rails['gitlab_shell_ssh_port'] = 22
gitlab_rails['gitlab_shell_git_timeout'] = 800
```
Monitoring and Alerting
1. Set Up Log Monitoring
```bash
Configure log rotation
sudo nano /etc/logrotate.d/gitlab
```
```
/var/log/gitlab//.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
copytruncate
}
```
2. Monitor System Resources
Create monitoring script:
```bash
#!/bin/bash
System monitoring script
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | awk -F'%' '{print $1}')
MEMORY_USAGE=$(free | grep Mem | awk '{printf("%.2f"), $3/$2 * 100.0}')
DISK_USAGE=$(df -h / | awk 'NR==2{printf "%s", $5}' | sed 's/%//')
echo "CPU Usage: ${CPU_USAGE}%"
echo "Memory Usage: ${MEMORY_USAGE}%"
echo "Disk Usage: ${DISK_USAGE}%"
Send alerts if thresholds exceeded
if (( $(echo "$CPU_USAGE > 80" | bc -l) )); then
echo "High CPU usage alert!" | mail -s "GitLab Server Alert" admin@your-domain.com
fi
```
Maintenance and Updates
Regular Maintenance Tasks
1. Update GitLab
```bash
Backup before updating
sudo gitlab-backup create
Update package lists
sudo apt update
Upgrade GitLab
sudo apt upgrade gitlab-ce
For CentOS/RHEL
sudo yum update gitlab-ce
```
2. Database Maintenance
```bash
Database vacuum and analyze
sudo gitlab-rails runner "
ActiveRecord::Base.connection.tables.each do |table|
puts \"Processing #{table}\"
ActiveRecord::Base.connection.execute(\"VACUUM ANALYZE #{table}\")
end
"
```
3. Clean Up Old Data
```bash
Clean up old artifacts
sudo gitlab-rails runner "
Ci::Build.where('created_at < ?', 30.days.ago).find_each do |build|
build.erase_artifacts!
end
"
Clean up old traces
sudo gitlab-ctl cleanup-build-trace-chunks
```
Version Upgrade Path
Always follow GitLab's upgrade path:
1. Check current version: `sudo gitlab-rake gitlab:env:info`
2. Review upgrade path: Consult GitLab documentation
3. Create backup: `sudo gitlab-backup create`
4. Upgrade incrementally: Don't skip major versions
5. Test thoroughly: Verify all features work after upgrade
Conclusion
Setting up GitLab on Linux provides your organization with a powerful, self-hosted DevOps platform. This comprehensive guide has covered everything from initial installation to advanced configuration, security hardening, and maintenance procedures.
Key takeaways from this guide:
- Proper planning is essential: Ensure your server meets hardware requirements and has all prerequisites installed
- Security should be a priority: Implement SSL/TLS, configure proper authentication, and follow security best practices
- Regular maintenance is crucial: Keep your GitLab installation updated, monitor performance, and maintain regular backups
- Documentation is your friend: Keep detailed records of your configuration changes and customizations
Next Steps
After successfully setting up GitLab, consider these next steps:
1. Create your first project and familiarize yourself with GitLab's interface
2. Set up CI/CD pipelines to automate your development workflow
3. Configure integrations with external tools like Slack, JIRA, or monitoring systems
4. Train your team on GitLab features and best practices
5. Implement advanced features like GitLab Pages, Container Registry, or Kubernetes integration
Remember that GitLab is a powerful platform with extensive capabilities. Take time to explore its features and customize it according to your organization's specific needs. Regular monitoring, maintenance, and staying updated with GitLab's latest features will ensure you get the most value from your installation.
For ongoing support and community resources, consider joining the GitLab community forum, following their documentation updates, and participating in GitLab user groups in your area. With proper setup and maintenance, your GitLab installation will serve as a robust foundation for your development and DevOps practices.