GitLab 是一款開源的代碼托管平臺,集代碼倉庫、持續集成與部署、代碼審查等功能于一體。本文將指導你在 CentOS 系統 上搭建 GitLab。
一、準備工作
1. 系統要求
操作系統:CentOS 7 或 CentOS 8
硬件要求:
CPU:2 核或以上
內存:4GB 或以上
磁盤:20GB 可用空間
2. 配置基礎環境
執行以下命令,更新系統并安裝基礎工具:
yum update -y
yum install -y curl policycoreutils-python openssh-server perl
二、安裝所需組件
1. 安裝 PostgreSQL
GitLab 使用 PostgreSQL 作為默認數據庫。安裝并初始化:
yum install -y postgresql-server
postgresql-setup initdb
systemctl enable postgresql
systemctl start postgresql
2. 安裝 Redis
Redis 用于緩存和其他 GitLab 服務:
yum install -y redis
systemctl enable redis
systemctl start redis
三、安裝 GitLab
1. 添加 GitLab 軟件源
使用官方腳本配置 GitLab 社區版(CE)軟件源:
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.rpm.sh | sudo bash
2. 安裝 GitLab
安裝 GitLab CE 并指定外部訪問地址:
EXTERNAL_URL="http://your-domain-or-ip" yum install -y gitlab-ce
3. 配置數據存儲路徑
修改 GitLab 配置文件/etc/gitlab/gitlab.rb:
git_data_dirs({
"default" => {
"path" => "/data/gitlab/git-data"
}
})
gitlab_rails['backup_path'] = "/data/gitlab/backups"
4. 啟動 GitLab
應用配置并啟動 GitLab:
gitlab-ctl reconfigure
gitlab-ctl restart
5. 查看初始密碼
GitLab 在初始化時會生成一個管理員賬號密碼,查看文件即可:
cat /etc/gitlab/initial_root_password
四、訪問 GitLab
在瀏覽器中輸入 http://your-domain-or-ip
使用 root 賬戶和生成的初始密碼登錄
登錄后可創建項目、管理用戶、配置 CI/CD 等
五、GitLab 常用命令
1. 服務管理
啟動 GitLab:gitlab-ctl start
停止 GitLab:gitlab-ctl stop
重啟 GitLab:gitlab-ctl restart
檢查服務狀態:gitlab-ctl status
2. 配置與日志
重新配置 GitLab:gitlab-ctl reconfigure
查看配置文件:cat /etc/gitlab/gitlab.rb
查看日志:less /var/log/gitlab/gitlab-rails/production.log
3. 數據備份與還原
手動備份:gitlab-rake gitlab:backup:create
還原備份:gitlab-rake gitlab:backup:restore
清理舊備份文件:gitlab-ctl cleanup
六、GitLab 組件說明
GitLab 是一個復雜的集成系統,主要組件如下:
組件
功能說明
Puma
運行 GitLab Rails 的 Web 應用服務器
Redis
用于緩存和會話管理
PostgreSQL
數據庫服務,存儲 GitLab 的核心數據
Nginx
靜態文件服務和反向代理
Sidekiq
后臺任務處理
Prometheus
系統監控與報警工具
Gitaly
提供 Git 倉庫服務,支持 Git 操作
七、GitLab 目錄結構
目錄位置
說明
/var/opt/gitlab/git-data/repositories倉庫存儲目錄
/opt/gitlabGitLab 安裝路徑
/etc/gitlab配置文件路徑
/var/log/gitlabGitLab 日志存儲路徑
/var/opt/gitlab/backups備份文件存儲目錄
八、最佳實踐
1. 定期備份
添加定時任務,每天自動備份:
crontab -e
# 添加以下內容,每天凌晨備份
0 0 * * * /opt/gitlab/bin/gitlab-rake gitlab:backup:create CRON=1
2. 啟用日志輪轉
防止日志文件過大:
gitlab-ctl logrotate
3. 優化性能
根據服務器配置,調整以下參數:
puma['worker_processes']:設置為 CPU 核心數
sidekiq['concurrency']:設置合適的并發數
4. 配置 SSL
啟用 HTTPS 確保傳輸安全:
在配置文件/etc/gitlab/gitlab.rb 中配置 SSL 證書路徑
重啟 GitLab:gitlab-ctl reconfigure
九、總結
本文介紹了在 CentOS 系統上安裝和配置 GitLab 的完整流程,包括組件介紹、目錄結構以及最佳實踐配置。完成這些步驟后,你將擁有一個功能強大的代碼托管平臺。如果有其他問題,歡迎在評論區討論!