Jenkins 自动化部署
2024/6/1大约 4 分钟
Jenkins 自动化部署
概述
Jenkins 是一个开源的持续集成和持续部署(CI/CD)工具,用于自动化构建、测试和部署软件项目。
1. 安装与配置
1.1 使用 Docker 安装
# 拉取 Jenkins 镜像
docker pull jenkins/jenkins:lts
# 创建数据目录
mkdir -p /var/jenkins_home
chown -R 1000:1000 /var/jenkins_home
# 启动容器
docker run -d \
--name jenkins \
-p 8080:8080 \
-p 50000:50000 \
-v /var/jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts1.2 初始配置
- 访问
http://localhost:8080 - 获取初始管理员密码:
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword- 安装推荐插件
- 创建管理员账号
1.3 安装必要插件
# 安装插件(通过 Jenkins UI 或 CLI)
# Git Plugin
# Pipeline Plugin
# Docker Plugin
# .NET Core SDK Plugin
# NodeJS Plugin2. 创建流水线
2.1 新建流水线任务
// Jenkinsfile
pipeline {
agent any
tools {
dotnet 'dotnet-8.x'
nodejs 'NodeJS-20.x'
}
stages {
stage('拉取代码') {
steps {
git branch: 'main', url: 'https://gitee.com/user/my-project.git'
}
}
stage('安装依赖') {
steps {
sh 'dotnet restore'
}
}
stage('构建项目') {
steps {
sh 'dotnet build --configuration Release'
}
}
stage('运行测试') {
steps {
sh 'dotnet test --no-build --configuration Release'
}
}
stage('发布项目') {
steps {
sh 'dotnet publish --configuration Release --output ./publish'
}
}
stage('部署到服务器') {
steps {
sshPublisher(publishers: [sshPublisherDesc(
configName: 'ProductionServer',
transfers: [sshTransfer(
sourceFiles: 'publish/**',
remoteDirectory: '/opt/my-project',
cleanRemote: false
)]
)])
}
}
}
post {
success {
echo '构建成功!'
// 发送通知
emailext to: 'dev@example.com',
subject: '构建成功 - ${JOB_NAME}',
body: '构建成功!'
}
failure {
echo '构建失败!'
emailext to: 'dev@example.com',
subject: '构建失败 - ${JOB_NAME}',
body: '构建失败!'
}
}
}2.2 多环境部署
pipeline {
agent any
parameters {
choice(
name: 'Environment',
choices: ['development', 'staging', 'production'],
description: '选择部署环境'
)
}
stages {
stage('构建') {
steps {
sh 'dotnet publish --configuration Release'
}
}
stage('部署') {
when {
expression { params.Environment == 'development' }
}
steps {
echo '部署到开发环境'
// 开发环境部署逻辑
}
}
stage('部署到测试环境') {
when {
expression { params.Environment == 'staging' }
}
steps {
echo '部署到测试环境'
// 测试环境部署逻辑
}
}
stage('部署到生产环境') {
when {
expression { params.Environment == 'production' }
}
steps {
input message: '确认部署到生产环境?'
echo '部署到生产环境'
// 生产环境部署逻辑
}
}
}
}3. 自动化部署脚本
3.1 发布脚本(Linux)
#!/bin/bash
# deploy.sh
APP_NAME="my-project"
APP_PATH="/opt/my-project"
BACKUP_PATH="/opt/backup"
# 创建备份
mkdir -p $BACKUP_PATH
tar -czf $BACKUP_PATH/$APP_NAME-$(date +%Y%m%d%H%M%S).tar.gz $APP_PATH
# 停止服务
systemctl stop $APP_NAME
# 复制新文件
cp -r ./publish/* $APP_PATH
# 启动服务
systemctl start $APP_NAME
# 检查服务状态
sleep 5
systemctl status $APP_NAME3.2 配置 systemd 服务
# /etc/systemd/system/my-project.service
[Unit]
Description=My Project Service
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/my-project
ExecStart=/usr/bin/dotnet /opt/my-project/MyProject.dll
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target# 启用服务
systemctl daemon-reload
systemctl enable my-project
systemctl start my-project4. 集成 Docker
4.1 Dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["MyProject.csproj", "."]
RUN dotnet restore "./MyProject.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "MyProject.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "MyProject.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyProject.dll"]4.2 流水线集成 Docker
stage('构建 Docker 镜像') {
steps {
script {
docker.build("my-project:${BUILD_NUMBER}")
}
}
}
stage('推送 Docker 镜像') {
steps {
script {
docker.withRegistry('https://registry.example.com', 'docker-credentials') {
docker.image("my-project:${BUILD_NUMBER}").push()
}
}
}
}
stage('部署容器') {
steps {
sh 'docker-compose up -d'
}
}5. 定时构建与触发器
5.1 定时构建
pipeline {
agent any
triggers {
// 每天凌晨2点执行
cron('0 2 * * *')
}
stages {
// ...
}
}5.2 GitHub/Gitee 触发器
- 在 Jenkins 中配置 GitHub/Gitee Webhook
- 在代码仓库中添加 Webhook URL:
http://jenkins.example.com/github-webhook/ - 选择触发事件:Push、Pull Request
5.3 手动触发
pipeline {
agent any
triggers {
// 允许手动触发
pollSCM('')
}
parameters {
booleanParam(name: 'SKIP_TESTS', defaultValue: false, description: '是否跳过测试')
}
stages {
stage('测试') {
when {
not { expression { params.SKIP_TESTS } }
}
steps {
sh 'dotnet test'
}
}
}
}6. 安全与权限
6.1 凭证管理
在 Jenkins 中添加凭证:
- 用户名/密码
- SSH 密钥
- API Token
- Docker Registry 凭证
在流水线中使用凭证:
pipeline {
agent any
environment {
GIT_CREDENTIALS = credentials('git-credentials')
SSH_CREDENTIALS = credentials('ssh-credentials')
}
stages {
stage('拉取代码') {
steps {
git branch: 'main',
url: "https://${GIT_CREDENTIALS}@gitee.com/user/my-project.git"
}
}
}
}6.2 角色权限管理
使用 Role-Based Access Control (RBAC) 插件管理用户权限:
- 安装 Role Strategy Plugin
- 创建角色:
- Admin(管理员)
- Developer(开发者)
- Viewer(查看者)
- 分配权限:
- 项目权限:构建、配置、删除
- 系统权限:管理、配置
7. 监控与告警
7.1 构建状态监控
pipeline {
agent any
stages {
// ...
}
post {
success {
slackSend channel: '#devops',
message: "构建成功: ${BUILD_URL}"
}
failure {
slackSend channel: '#devops',
message: "构建失败: ${BUILD_URL}"
}
}
}7.2 邮件通知
post {
always {
emailext attachLog: true,
to: 'dev-team@example.com',
subject: "构建 ${BUILD_STATUS}: ${JOB_NAME}",
body: """
项目: ${JOB_NAME}
构建号: ${BUILD_NUMBER}
状态: ${BUILD_STATUS}
日志: ${BUILD_URL}console
"""
}
}8. 性能优化
8.1 并行构建
pipeline {
agent any
stages {
stage('并行测试') {
parallel {
stage('单元测试') {
steps {
sh 'dotnet test --filter Category=Unit'
}
}
stage('集成测试') {
steps {
sh 'dotnet test --filter Category=Integration'
}
}
stage('UI测试') {
steps {
sh 'npm run test'
}
}
}
}
}
}8.2 缓存依赖
pipeline {
agent any
options {
cache(path: '**/node_modules', key: 'node_modules-${MD5SUM(package-lock.json)}')
cache(path: '**/packages', key: 'packages-${MD5SUM(packages.lock.json)}')
}
stages {
stage('安装依赖') {
steps {
sh 'npm ci'
sh 'dotnet restore'
}
}
}
}总结
Jenkins 是一个功能强大的 CI/CD 工具,可以自动化构建、测试和部署流程。合理配置可以显著提高开发效率和部署质量。
作者:Blogger
日期:2024年6月1日