CI/CD 落地实录:从 0 到 1 搭建 GitHub Actions 流水线
我们团队从手动部署切换到 CI/CD 用了两周。下面是从零搭建的完整记录。
第 1 步:确定流水线结构
CODE
代码推送 → 安装依赖 → 代码检查 → 测试 → 构建 → 部署第 2 步:基础配置
YAML
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test-and-deploy:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_PASSWORD: test
options: >-
--health-cmd pg_isready
--health-interval 10s
ports:
- 5432:5432
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm run type-check
- run: npm test
env:
DATABASE_URL: postgresql://postgres:test@localhost:5432/test
- run: npm run build第 3 步:缓存优化
YAML
- uses: actions/cache@v4
with:
path: |
~/.npm
${{ github.workspace }}/.next/cache
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-nextjs-第 4 步:部署到服务器
YAML
- name: Deploy to server
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
cd /app
git pull origin main
docker compose up -d --build第 5 步:环境区分
YAML
# 开发环境 - 推送到 dev 分支自动部署
name: Deploy Dev
on:
push:
branches: [dev]
# 生产环境 - 手动触发
name: Deploy Production
on:
workflow_dispatch: # 手动触发第 6 步:通知
YAML
- name: Notify on failure
if: failure()
uses: slackapi/slack-github-action@v1
with:
payload: |
{
"text": "部署失败: ${{ github.event.head_commit.message }}"
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}关键经验
1. 先跑 lint 再跑 test,lint 更快,先拦截低级错误
2. 缓存 node_modules,每次全量安装太慢
3. 敏感信息用 Secrets,不要硬编码
4. 生产部署用手动触发,不要自动
5. 失败时通知,别等别人告诉你部署挂了
读者评论 2