docs: add comprehensive Jenkins CI/CD setup guide

- Step-by-step configuration for Pipeline job
- Gitea Webhook integration instructions
- SSH deployment credentials setup
- Notification configuration (email/DingTalk)
- Troubleshooting common issues
- Performance optimization tips
This commit is contained in:
张翔
2026-05-12 12:50:05 +08:00
parent 8840c4398a
commit 9c9f2276f2
+467
View File
@@ -0,0 +1,467 @@
# Jenkins CI/CD 配置指南
## 📋 概述
本文档指导你如何在 Jenkins 中配置自动化 CI/CD 流水线,实现:
- ✅ Gitea Webhook 自动触发构建
- ✅ 多阶段质量门禁(Lint + TypeCheck + Test + Build
- ✅ 自动部署到生产服务器
- ✅ 构建通知(邮件/钉钉/企业微信)
---
## 🔧 前置条件
### 1. Jenkins 插件安装
确保以下插件已安装在 Jenkins 中:
| 插件名称 | 用途 | 必需 |
|---------|------|------|
| **Pipeline** | 支持 Jenkinsfile 流水线 | ✅ 是 |
| **Git Plugin** | Git 仓库集成 | ✅ 是 |
| **Generic Webhook Trigger** | Gitea Webhook 触发 | ✅ 是 |
| **NodeJS Plugin** | Node.js 环境管理 | ✅ 是 |
| **HTML Publisher** | 发布测试报告 | ✅ 是 |
| **SSH Agent Plugin** | SSH 部署连接 | ✅ 是 |
| **Email Extension** | 邮件通知 | ⚠️ 可选 |
| **DingTalk Plugin** | 钉钉通知 | ⚠️ 可选 |
#### 安装步骤:
1. 登录 Jenkins`http://<your-jenkins-ip>:8080`
2. 导航到:**Manage Jenkins → Plugins → Available plugins**
3. 搜索并安装上述插件
4. 重启 Jenkins
### 2. 全局工具配置
#### 配置 Node.js
1. **Manage Jenkins → Tools**
2. 找到 **NodeJS** 部分
3. 点击 **Add NodeJS**
4. 配置如下:
```
Name: Node.js 18
Install automatically: ✅ 勾选
Version: 18.20.x (LTS)
```
5. 点击 **Save**
#### 配置 Git
1. 同样在 **Tools** 页面
2. 找到 **Git** 部分
3. 确保 Git 路径正确(通常 `/usr/bin/git`
4. 如果未安装,选择 **Install automatically**
---
## 🚀 创建 Pipeline 任务
### 方法 A:通过 Jenkins UI 创建(推荐新手)
#### 步骤 1:创建新任务
1. 点击 **New Item**
2. 输入任务名称:`novalon-website-ci-cd`
3. 选择 **Pipeline**
4. 点击 **OK**
#### 步骤 2:配置 General
```
☑️ This project is parameterized (勾选)
Parameters:
┌─ Boolean Parameter
│ Name: DEPLOY_TO_PRODUCTION
│ Default Value: false
│ Description: 是否部署到生产环境(仅在 main 分支且测试通过后可用)
└──────────────────────────────
☑️ GitHub project (可选)
Project URL: https://git.f.novalon.cn/novalon/novalon-website
```
#### 步骤 3:配置 Build Triggers(触发器)
##### 选项 1Gitea Webhook 触发(推荐)
1. 勾选 **Trigger builds remotely**
2. 设置 Authentication Token`novalon-website-ci-token`
3.**Build Triggers** 部分找到 **Generic Webhook Trigger****Gitea Webhook**
- 如果使用 **Generic Webhook Trigger** 插件:
```
Token: novalon-website-ci-token
```
4. **保存任务后,获取 Webhook URL**
```
http://<jenkins-ip>:8080/generic-webhook-trigger/invoke?token=novalon-website-ci-token
```
##### 选项 2:轮询 SCM(备选)
```
☑️ Poll SCM
Schedule: H/15 * * * * (每 15 分钟检查一次)
```
#### 步骤 4:配置 Pipeline(流水线定义)
选择 **Pipeline script from SCM**
```
SCM: Git
Repositories:
Repository URL: https://git.f.novalon.cn/novalon/novalon-website.git
Credentials: (添加 Gitea 凭据)
Branch: */dev (或 */main)
Script Path: Jenkinsfile
Lightweight checkout: ☑️ 勾选
```
#### 步骤 5:添加凭据(Credentials
1. 点击 **Add → Jenkins**
2. 选择 **Username with password**
3. 输入 Gitea 账号密码:
- Username: `你的 Gitea 用户名`
- Password: `你的 Gitea 密码或 Personal Access Token`
4. ID: `gitea-credentials`(自定义)
5. 点击 **Add**
#### 步骤 6:保存并测试
1. 点击 **Save** 保存配置
2. 点击 **Build Now** 手动触发一次构建
3. 查看控制台输出确认流程正常
---
### 方法 BPipeline as CodeJenkinsfile 已包含)
由于项目根目录已包含 [Jenkinsfile](../Jenkinsfile)Jenkins 会自动读取。
只需确保:
1. ✅ Jenkinsfile 在仓库根目录
2. ✅ Pipeline 任务指向正确的分支和 Jenkinsfile 路径
3. ✅ 所需插件已安装
---
## 🔗 配置 Gitea Webhook
### 步骤 1:在 Gitea 中创建 Webhook
1. 打开 Gitea 仓库:`https://git.f.novalon.cn/novalon/novalon-website`
2. 点击 **Settings → Webhooks → Add Webhook → Gitea**
3. 配置如下:
```
Target URL:
http://<your-jenkins-ip>:8080/generic-webhook-trigger/invoke?token=novalon-website-ci-token
HTTP Method: POST
Content Type: application/json
Secret: (留空或设置密钥)
Trigger On:
☑️ Push Events
☐ Create Events
☐ Pull Request Events (可选)
☐ Tag Events (可选)
Branch Filter:
dev, main, develop (逗号分隔,留空表示所有分支)
Active: ☑️ 勾选
```
4. 点击 **Add Webhook**
### 步骤 2:测试 Webhook
1. 在 Webhook 列表中,点击刚创建的 Webhook
2. 点击 **Test Delivery → Push Event**
3. 查看 **Recent Deliveries** 确认状态为 **200 OK**
4. 检查 Jenkins 是否收到触发并开始构建
---
## 🔐 配置部署凭据(SSH
### 步骤 1:生成 SSH 密钥对(如果还没有)
```bash
# 在 Jenkins 服务器上执行
ssh-keygen -t rsa -b 4096 -C "jenkins@novalon" -f ~/.ssh/jenkins_deploy_key
```
### 步骤 2:将公钥添加到生产服务器
```bash
# 复制公钥内容
cat ~/.ssh/jenkins_deploy_key.pub
# 在生产服务器(139.155.109.62)上执行
echo "公钥内容" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
```
### 步骤 3:在 Jenkins 中添加 SSH 凭据
1. **Manage Jenkins → Credentials → System → Global credentials**
2. **Add Credentials → SSH Username with private key**
3. 配置:
```
ID: deploy-server-ssh
Username: root
Private Key:
☑️ Enter directly
(粘贴私钥内容:~/.ssh/jenkins_deploy_key 的内容)
Passphrase: (如果有则填写,否则留空)
```
4. 点击 **Save**
### 步骤 4:更新 Jenkinsfile 使用凭据
编辑 [Jenkinsfile](../Jenkinsfile) 中的部署阶段,添加:
```groovy
stage('🚀 部署到生产环境') {
when {
allOf {
anyOf { branch 'main'; branch 'develop' }
expression { return params.DEPLOY_TO_PRODUCTION }
}
}
steps {
sshagent(['deploy-server-ssh']) {
sh '''
# 部署命令...
'''
}
}
}
```
---
## 📧 配置通知
### 选项 1:邮件通知
1. **Manage Jenkins → System**
2. 找到 **E-mail Notification** 部分:
```
SMTP server: smtp.qq.com (或你的 SMTP 服务器)
SMTP Port: 465
Use SSL: ☑️
Username: your-email@qq.com
Password: 你的授权码(不是 QQ 密码)
Reply-To Address: your-email@qq.com
Charset: UTF-8
```
3. 点击 **Test configuration** 发送测试邮件
4. 点击 **Save**
### 选项 2:钉钉机器人通知(推荐国内团队)
1. 创建钉钉群机器人:
- 打开钉钉群 → 设置 → 智能群助手 → 添加机器人
- 选择 **Custom(通过 Webhook 地址接入)**
- 复制 Webhook URL`https://oapi.dingtalk.com/robot/send?access_token=xxx`
2. 安装 **DingTalk Plugin**(或在 Jenkinsfile 中使用 curl):
在 Jenkinsfile 的 `post { always {} }` 部分添加:
```groovy
post {
always {
script {
def webhookUrl = 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN'
def message = """
{
"msgtype": "markdown",
"markdown": {
"title": "Jenkins 构建通知",
"text": "## Jenkins 构建通知\\n> 项目:${env.PROJECT_NAME}\\n> 分支:${env.GIT_BRANCH}\\n> 构建号:#${env.BUILD_NUMBER}\\n> 状态:${currentBuild.result ?: 'SUCCESS'}\\n> 时间:${new Date().format('yyyy-MM-dd HH:mm:ss')}"
}
}
"""
sh "curl -s -X POST '${webhookUrl}' -H 'Content-Type: application/json' -d '${message}'"
}
}
}
```
---
## 🧪 手动触发构建验证
### 第一次构建建议手动触发:
1. 进入任务页面:`novalon-website-ci-cd`
2. 点击 **Build Now**
3. 点击正在运行的构建号查看实时日志
4. 确认以下阶段成功:
```
✅ Stage 1: 🔧 环境准备
✅ Stage 2: 📥 安装依赖
✅ Stage 3: 🔍 ESLint 检查
✅ Stage 4: 🔍 TypeScript 类型检查
✅ Stage 5: 🧪 单元测试 + 覆盖率
✅ Stage 6: 🏗️ 生产构建
⏭️ Stage 7: 🧪 E2E 测试(需要 Playwright 浏览器)
⏭️ Stage 8: ⚡ 性能测试(需要 k6)
⏭️ Stage 9: 🚀 部署(需要勾选 DEPLOY_TO_PRODUCTION 参数)
```
### 查看构建产物:
1. 点击完成的构建号
2. 左侧菜单查看:
- **Console Output** - 完整日志
- **Coverage Report (Jest)** - 测试覆盖率报告
- **Edit Build Information** - 构建元数据
---
## 🔄 常见问题排查
### 问题 1Webhook 未触发构建
**症状**:推送代码后 Jenkins 无反应
**解决方案**
1. 检查 Gitea Webhook 的 **Recent Deliveries** 状态码是否为 200
2. 确认 Jenkins URL 正确且可从 Gitea 访问
3. 检查 Jenkins 安全设置(Configure Global Security):
- CSRF Protection → Enable proxy compatibility
- Allow anonymous read access(如果需要)
### 问题 2Node.js 版本错误
**症状**`ERROR: Node.js version not found`
**解决方案**
1. 确认已在 **Manage Jenkins → Tools** 中配置 Node.js 18
2. 检查 Jenkinsfile 中的 `nodejs(nodeJSInstallationName: '18')` 名称匹配
### 问题 3npm install 失败
**症状**`npm ERR! network error`
**解决方案**
1. 检查 npm registry 配置(默认使用 npmmirror 镜像)
2. 如果是私有包,配置 `.npmrc` 文件
3. 检查 Jenkins 服务器的网络连接
### 问题 4SSH 部署失败
**症状**`Permission denied (publickey)`
**解决方案**
1. 确认 SSH 私钥已正确添加到 Jenkins 凭据
2. 确认生产服务器的 `~/.ssh/authorized_keys` 包含对应公钥
3. 测试 SSH 连接:`ssh root@139.155.109.62`
### 问题 5ESLint 或 TypeScript 检查失败
**症状**:构建在代码质量检查阶段失败
**解决方案**
1. 查看完整错误日志
2. 在本地运行修复:
```bash
npm run lint --fix
npm run type-check
```
3. 修复问题后重新提交代码
---
## 📊 监控与优化
### 构建历史分析
1. 进入任务主页
2. 查看构建趋势图(成功率、平均耗时)
3. 识别瓶颈阶段(通常是安装依赖或测试)
### 性能优化建议
1. **启用构建缓存**
```groovy
environment {
CI_CACHE_PATH = "${HOME}/.cache/novalon-website"
}
```
2. **并行化测试**:在 Jenkinsfile 中使用 `parallel` 执行多个测试套件
3. **增量构建**:只对变更的模块运行测试(需要 monorepo 结构)
4. **Docker 化构建环境**:使用 Docker agent 保证一致性
---
## ✅ 完成清单
完成以下所有项后,CI/CD 流水线即可正常运行:
- [x] 推送代码到 Gitea ✅
- [ ] 安装 Jenkins 必要插件
- [ ] 配置全局工具(Node.js 18, Git
- [ ] 创建 Pipeline 任务(指向 dev 分支的 Jenkinsfile
- [ ] 添加 Gitea 凭据(Username with Password
- [ ] 配置 Gitea WebhookPush Events → Jenkins Generic Trigger
- [ ] 添加部署 SSH 凭据(生产服务器访问权限)
- [ ] 配置通知渠道(邮件/钉钉)
- [ ] 手动触发首次构建验证
- [ ] 确认所有阶段成功通过
- [ ] 测试自动触发(推送代码 → Jenkins 自动构建)
---
## 🎯 下一步操作
### 立即执行:
1. **登录 Jenkins 并按照上述步骤创建任务**
2. **配置 Gitea Webhook**
3. **手动触发第一次构建**
4. **查看构建日志确认流程正常**
### 本周内完成:
1. **设置构建失败告警**
2. **建立定期审查机制(每周审查构建成功率)**
3. **优化构建性能(目标:<10 分钟完成全流程)**
---
## 📞 技术支持
如遇到问题,请检查:
1. **Jenkins 系统日志**`Manage Jenkins → System Log`
2. **Gitea Webhook 日志**Webhook 页面的 Recent Deliveries
3. **构建控制台输出**:每次构建的 Console Output
---
**文档版本**: v1.0
**最后更新**: 2026-01-15
**适用版本**: Jenkins 2.400+, Gitea 1.19+