预约咨询 提交工单

CI/CD 流水线搭建(GitHub Actions + 服务器部署)

手动部署既繁琐又容易出错。本文搭建完整的 CI/CD 流水线:代码提交 → 自动测试 → 构建镜像 → 部署到服务器。 GitHub Actions 工作流 yaml name: Deploy to Production on: push: branches: [ main ] jobs: build and deploy: runs on: ubuntu

CI/CD 流水线搭建(GitHub Actions + 服务器部署)
企业服务 Linux

项目背景与挑战

手动部署既繁琐又容易出错。本文搭建完整的 CI/CD 流水线:代码提交 → 自动测试 → 构建镜像 → 部署到服务器。 GitHub Actions 工作流 yaml name: Deploy to Production on: push: branches: [ main ] jobs: build and deploy: runs on: ubuntu

解决方案

手动部署既繁琐又容易出错。本文搭建完整的 CI/CD 流水线:代码提交 → 自动测试 → 构建镜像 → 部署到服务器。 GitHub Actions 工作流 yaml name: Deploy to Production on: push: branches: [ main ] jobs: build and deploy: runs on: ubuntu

交付结果

详细说明

手动部署既繁琐又容易出错。本文搭建完整的 CI/CD 流水线:代码提交 → 自动测试 → 构建镜像 → 部署到服务器。

GitHub Actions 工作流

name: Deploy to Production

on:
  push:
    branches: [ main ]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4

    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: 18

    - name: Install dependencies
      run: npm ci

    - name: Run tests
      run: npm test

    - name: Build Docker image
      run: |
        docker build -t opsglobal:latest .
        docker save opsglobal:latest > opsglobal.tar

    - name: Deploy to server
      uses: appleboy/scp-action@v0.1.7
      with:
        host: ${{ secrets.SERVER_HOST }}
        username: ${{ secrets.SERVER_USER }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        source: "opsglobal.tar,docker-compose.yml"
        target: "/opt/opsglobal"

    - name: Restart services
      uses: appleboy/ssh-action@v1.0.0
      with:
        host: ${{ secrets.SERVER_HOST }}
        username: ${{ secrets.SERVER_USER }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        script: |
          cd /opt/opsglobal
          docker load < opsglobal.tar
          docker-compose up -d

服务器部署脚本

#!/bin/bash
set -e

git pull origin main
npm ci
npm run build
sudo systemctl restart opsglobal
curl -f http://localhost:3000/health || exit 1

echo "Deployment complete!"

实用技巧

  • 使用 GitHub Secrets 管理敏感信息
  • 配置蓝绿部署或滚动更新减少停机时间
  • 部署失败自动回滚(保留上一个版本的 Docker 镜像标签)
!

你的系统也遇到类似问题?

我们可以根据你的实际环境复用类似排查思路,提供远程诊断、修复、优化和交付报告。

工单 WhatsApp 联系 咨询