💡知行合一.🐬|

BaldButStrong

园龄:2年11个月粉丝:2关注:0

2025-02-11 13:52阅读: 15评论: 0推荐: 0

Jenkins CICD部署

Jenkins 部署 CI/CD 的详细步骤指南:

1. Jenkins 安装

1.1 环境要求

  • Java 8 或 11(推荐 JDK11)
  • 系统:Linux/Windows/macOS

1.2 安装方法(Ubuntu 示例)

# 安装 Java
sudo apt install openjdk-11-jdk
# 添加 Jenkins 仓库
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
# 安装 Jenkins
sudo apt update
sudo apt install jenkins
# 启动服务
sudo systemctl start jenkins
sudo systemctl enable jenkins

访问 http://<服务器IP>:8080 完成初始化配置。

2. Jenkins 基础配置

2.1 插件管理

  1. 登录后进入 Manage Jenkins > Plugins
  2. 安装必要插件:
    • Git Parameter
    • Pipeline
    • Docker
    • Blue Ocean
    • SSH Pipeline Steps
    • 代码仓库插件(GitHub/GitLab)

2.2 工具配置

进入 Manage Jenkins > Global Tool Configuration

  • 添加 JDK、Maven、Gradle 等工具的自动安装配置
  • 配置 Docker 路径(默认 /usr/bin/docker

3. 创建 CI/CD Pipeline

3.1 新建 Pipeline 任务

  1. 新建 Item > 选择 Pipeline
  2. 配置参数:
    • 参数化构建:添加 Git 分支参数
    • SCM:配置 Git 仓库地址和凭证
    • 触发器:设置 Webhook 或定时构建

3.2 Webhook 配置示例(GitHub)

  1. 在 GitHub 仓库设置中添加 Webhook:
    • Payload URL: http://<jenkins-url>/github-webhook/
    • Content type: application/json
  2. Jenkins 任务中配置触发器:
    • GitHub hook trigger for GITScm polling

4. Pipeline 脚本示例(声明式)

pipeline {
agent any
environment {
DOCKER_REGISTRY = "registry.example.com"
PROJECT_VERSION = "1.0.${BUILD_NUMBER}"
}
stages {
stage('Checkout') {
steps {
git branch: 'main',
url: 'https://github.com/yourrepo/application.git'
}
}
stage('Build') {
steps {
sh 'mvn clean package -DskipTests'
}
}
stage('Test') {
steps {
sh 'mvn test'
junit '**/target/surefire-reports/*.xml'
}
}
stage('Docker Build') {
steps {
script {
docker.build("${DOCKER_REGISTRY}/app:${PROJECT_VERSION}")
}
}
}
stage('Deploy to Staging') {
when {
branch 'main'
}
steps {
sshagent(['staging-server']) {
sh """
scp target/*.jar user@staging:/app/
ssh user@staging "sudo systemctl restart app-service"
"""
}
}
}
stage('Production Deployment') {
when {
expression {
return env.BRANCH_NAME == 'main' &&
currentBuild.resultIsBetterOrEqualTo('SUCCESS')
}
}
steps {
timeout(time: 15, unit: 'MINUTES') {
input message: 'Deploy to production?', ok: 'Confirm'
}
kubernetesApply(
kubeconfigId: 'prod-cluster',
configs: 'k8s/deployment.yaml'
)
}
}
}
post {
success {
slackSend channel: '#ci-cd',
message: "Build ${BUILD_NUMBER} succeeded ✅"
}
failure {
mail to: 'team@example.com',
subject: "Build ${BUILD_NUMBER} Failed",
body: "Check console output at ${BUILD_URL}"
}
}
}

5. 高级部署技巧

5.1 金丝雀发布(Canary Release)

stage('Canary Deployment') {
steps {
script {
// 部署 10% 流量
sh 'kubectl apply -f canary-deployment.yaml'
sleep(time: 300, unit: 'SECONDS') // 监控期
// 根据监控结果决定是否全量发布
if (metricsAPI.getErrorRate() < 0.01) {
sh 'kubectl apply -f full-deployment.yaml'
} else {
error "Canary deployment failed"
}
}
}
}

5.2 自动回滚机制

post {
failure {
script {
if (currentStage == 'production') {
sshagent(['prod-server']) {
sh """
ssh user@prod "kubectl rollout undo deployment/app"
"""
}
}
}
}
}

6. 安全加固建议

  1. 权限控制
    • 使用 Role-Based Access Control (RBAC)
    • 创建不同权限级别的用户组
  2. 凭证管理
    • 使用 Jenkins Credentials 存储敏感信息
    • 限制凭证的作用域
  3. 审计日志
    • 启用 Audit Trail 插件
    • 集成 ELK 进行日志分析

7. 性能优化

  1. 分布式构建
    • 添加多个 Agent 节点
    • 使用 Kubernetes 插件动态创建 Pod
  2. 缓存策略
    • Maven/Gradle 依赖缓存
    • Docker 层缓存
  3. 并行执行
stage('Parallel Tests') {
parallel {
stage('Unit Tests') {
steps { sh './run_unit_tests.sh' }
}
stage('Integration Tests') {
steps { sh './run_integration_tests.sh' }
}
}
}

8. 监控与告警

  1. 集成 Prometheus:
    • 安装 Prometheus 插件
    • 配置 metrics 端点
  2. Grafana 仪表盘:
    • 监控构建成功率
    • 构建时长趋势分析
    • 资源利用率监控

常见问题排查

  1. 构建卡顿

    • 检查 Jenkins Master 内存设置(JAVA_OPTS="-Xmx4g -XX:MaxRAMPercentage=70.0"
    • 查看磁盘空间(/var/lib/jenkins
  2. SSH 连接失败

    • 检查 ~/.ssh/config 中的 StrictHostKeyChecking 设置
    • 验证 SSH 私钥格式(需 PEM 格式)
  3. Docker 权限问题

    # 将 Jenkins 用户加入 docker 组
    sudo usermod -aG docker jenkins
    sudo systemctl restart jenkins

通过以上步骤,您可以建立完整的 CI/CD 流程,并根据项目需求调整各阶段任务。建议结合具体业务场景逐步完善自动化测试、安全扫描(SAST/DAST)和质量门禁等环节。

本文作者:BaldButStrong

本文链接:https://www.cnblogs.com/supersimple/p/18709604

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   BaldButStrong  阅读(15)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起