在Debian上實現Rust項目的持續集成(CI)與部署(CD),可借助GitHub Actions、GitLab CI/CD等工具,以下是具體步驟:
在項目根目錄下創建.github/workflows/rust-ci.yml,定義CI/CD流程:
name: Rust CI/CD
on:
push:
branches: [main] # 觸發條件:推送到main分支
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4 # 檢出代碼
- name: Install Rust
run: rustup default stable # 安裝Rust穩定版
- name: Build
run: cargo build --release # 編譯項目
- name: Run tests
run: cargo test --verbose # 運行測試
deploy:
runs-on: ubuntu-latest
needs: build # 依賴構建成功
if: github.ref == 'refs/heads/main' # 僅main分支觸發部署
steps:
- uses: actions/checkout@v4
- name: Deploy to server
run: scp target/release/your_app user@your-server:/path/to/deploy # 部署二進制文件
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }} # 使用GitHub Secrets存儲私鑰
說明:
rustup安裝Rust工具鏈,cargo完成構建與測試。scp將二進制文件傳輸至服務器,需在GitHub Secrets中配置SSH密鑰。Swatinem/rust-cache緩存依賴,減少重復下載:- uses: Swatinem/rust-cache@v2
cargo nextest run --all-features。在Debian服務器上執行:
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash
sudo apt install gitlab-runner
sudo gitlab-runner register --non-interactive --executor "docker" --docker-image rust:latest
說明:注冊Runner時需關聯GitLab項目,并指定rust:latest鏡像。
.gitlab-ci.ymlstages:
- build
- test
- deploy
build:
stage: build
script:
- rustup default stable
- cargo build --release
test:
stage: test
script:
- cargo test --verbose
deploy:
stage: deploy
script:
- scp target/release/your_app user@your-server:/path/to/deploy
only:
- main # 僅main分支觸發部署
說明:
only關鍵字限制部署階段僅在main分支觸發。rust:latest鏡像)。runs-on中指定ubuntu-latest或macos-latest,并利用cross工具交叉編譯。通過上述配置,可實現Rust項目在Debian環境下的自動化構建、測試與部署,顯著提升開發效率與交付可靠性。