一、前置準備:安裝并配置GitLab
在Linux服務器上部署GitLab是實現項目托管的基礎,需完成以下步驟:
sudo apt update && sudo apt upgrade
);安裝必要依賴(curl
、openssh-server
、ca-certificates
、tzdata
、postfix
,其中postfix用于郵件通知)。curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash
,CentOS執行類似rpm命令);安裝GitLab CE(社區版):sudo apt install gitlab-ce
(Ubuntu)或sudo yum install gitlab-ce
(CentOS)。/etc/gitlab/gitlab.rb
設置外部訪問URL(如EXTERNAL_URL="http://your_server_ip"
);運行sudo gitlab-ctl reconfigure
應用配置;啟動服務(sudo gitlab-ctl start
)并設置開機自啟(sudo systemctl enable gitlab-ce
)。二、配置GitLab Runner(CI/CD執行引擎)
GitLab Runner是執行.gitlab-ci.yml
中任務的工具,需在Linux服務器(部署目標服務器)上安裝并注冊:
curl -L --output /etc/apt/trusted.gpg.d/gitlab.asc https://packages.gitlab.com/gitlab/gitlab-runner/gpgkey
echo "deb https://packages.gitlab.com/gitlab/gitlab-runner/ubuntu $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/gitlab-runner.list
sudo apt update && sudo apt install gitlab-runner -y
sudo gitlab-runner register
,按提示輸入:
http://your_gitlab_server_ip
);linux
,用于匹配項目中的標簽限制)。三、創建.gitlab-ci.yml(CI/CD流程定義)
在項目根目錄下創建.gitlab-ci.yml
文件,定義構建→測試→部署的自動化流程。以下是一個Java項目的示例:
stages:
- build # 構建階段:編譯代碼
- test # 測試階段:運行單元測試
- deploy # 部署階段:推送代碼到生產服務器
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository" # Maven本地倉庫路徑
build_job:
stage: build
script:
- echo "開始構建項目..."
- mvn clean package -DskipTests # 編譯并跳過測試(測試由單獨階段執行)
artifacts: # 將構建產物(如jar包)傳遞給后續階段
paths:
- target/*.jar
only:
- master # 僅master分支觸發
test_job:
stage: test
script:
- echo "運行單元測試..."
- mvn test # 執行測試用例
only:
- master
deploy_job:
stage: deploy
script:
- echo "開始部署到生產服務器..."
- scp -o StrictHostKeyChecking=no target/*.jar user@your_production_server:/opt/app/ # 使用scp傳輸文件
- ssh user@your_production_server "cd /opt/app && nohup java -jar *.jar > app.log 2>&1 &" # 后臺啟動應用
only:
- master
when: manual # 手動觸發部署(避免自動部署風險,可選)
關鍵說明:
stages
:定義流程階段順序,需按build→test→deploy
依次執行;script
:每個階段的執行命令(如mvn package
、scp
);artifacts
:將前一階段的輸出(如jar包)傳遞給后續階段;only
:指定觸發分支(如master
),避免其他分支誤觸發;when: manual
:手動觸發部署,適合生產環境風險控制。四、配置SSH免密登錄(Runner訪問目標服務器)
為了讓Runner能通過scp
/ssh
將代碼部署到目標Linux服務器,需配置SSH免密登錄:
ssh-keygen -t rsa
,按提示保存密鑰(默認路徑~/.ssh/id_rsa
),無需設置密碼。ssh-copy-id user@your_production_server
(user
為目標服務器用戶名),將公鑰添加到目標服務器的~/.ssh/authorized_keys
文件中。ssh user@your_production_server
,若無需輸入密碼即可登錄,則配置成功。五、觸發CI/CD流程
完成上述配置后,每次向GitLab項目的master
分支提交代碼(或合并Pull Request),GitLab會自動觸發CI/CD流水線:
六、進階優化(可選)
.gitlab-ci.yml
中配置緩存,加快構建速度(如緩存Maven的localRepository
或Node.js的node_modules
):cache:
paths:
- .m2/repository/ # Maven緩存
- node_modules/ # Node.js緩存
image: maven:3.8.6-openjdk-11
),避免環境差異問題;或通過Docker構建應用鏡像并推送到鏡像倉庫(如Docker Hub)。kubectl
命令實現滾動更新、自動擴縮容等高級部署功能(需配置KUBECONFIG
變量指向kubeconfig文件)。.gitlab-ci.yml
中添加通知步驟(如郵件、Slack),在流水線失敗時及時通知團隊:notify_job:
stage: .post # 在所有階段后執行
script:
- echo "發送失敗通知..."
- curl -X POST -H 'Content-type: application/json' --data '{"text":"Pipeline failed!"}' $SLACK_WEBHOOK_URL
when: on_failure
需提前在GitLab CI/CD Variables中配置SLACK_WEBHOOK_URL
(敏感信息建議使用變量而非硬編碼)。