Jenkins Automated Deployment
6/1/24About 3 min
Jenkins Automated Deployment
Overview
Jenkins is an open-source continuous integration and continuous deployment (CI/CD) tool for automating the build, test, and deployment of software projects.
1. Installation and Configuration
1.1 Install with Docker
# Pull Jenkins image
docker pull jenkins/jenkins:lts
# Create data directory
mkdir -p /var/jenkins_home
chown -R 1000:1000 /var/jenkins_home
# Start container
docker run -d \
--name jenkins \
-p 8080:8080 \
-p 50000:50000 \
-v /var/jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts1.2 Initial Setup
- Visit
http://localhost:8080 - Get the initial admin password:
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword- Install recommended plugins
- Create an admin account
1.3 Install Required Plugins
# Install plugins (via Jenkins UI or CLI)
# Git Plugin
# Pipeline Plugin
# Docker Plugin
# .NET Core SDK Plugin
# NodeJS Plugin2. Create a Pipeline
2.1 New Pipeline Job
// 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 '构建成功!'
// Send notification
emailext to: 'dev@example.com',
subject: '构建成功 - ${JOB_NAME}',
body: '构建成功!'
}
failure {
echo '构建失败!'
emailext to: 'dev@example.com',
subject: '构建失败 - ${JOB_NAME}',
body: '构建失败!'
}
}
}2.2 Multi-Environment Deployment
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 '部署到开发环境'
// Development environment deployment logic
}
}
stage('部署到测试环境') {
when {
expression { params.Environment == 'staging' }
}
steps {
echo '部署到测试环境'
// Staging environment deployment logic
}
}
stage('部署到生产环境') {
when {
expression { params.Environment == 'production' }
}
steps {
input message: '确认部署到生产环境?'
echo '部署到生产环境'
// Production environment deployment logic
}
}
}
}3. Automated Deployment Scripts
3.1 Deployment Script (Linux)
#!/bin/bash
# deploy.sh
APP_NAME="my-project"
APP_PATH="/opt/my-project"
BACKUP_PATH="/opt/backup"
# Create backup
mkdir -p $BACKUP_PATH
tar -czf $BACKUP_PATH/$APP_NAME-$(date +%Y%m%d%H%M%S).tar.gz $APP_PATH
# Stop service
systemctl stop $APP_NAME
# Copy new files
cp -r ./publish/* $APP_PATH
# Start service
systemctl start $APP_NAME
# Check service status
sleep 5
systemctl status $APP_NAME3.2 Configure systemd Service
# /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# Enable service
systemctl daemon-reload
systemctl enable my-project
systemctl start my-project4. Docker Integration
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 Pipeline Docker Integration
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. Scheduled Builds and Triggers
5.1 Scheduled Builds
pipeline {
agent any
triggers {
// Run daily at 2:00 AM
cron('0 2 * * *')
}
stages {
// ...
}
}5.2 GitHub/Gitee Triggers
- Configure GitHub/Gitee Webhook in Jenkins
- Add Webhook URL in the repository:
http://jenkins.example.com/github-webhook/ - Select trigger events: Push, Pull Request
5.3 Manual Trigger
pipeline {
agent any
triggers {
// Allow manual trigger
pollSCM('')
}
parameters {
booleanParam(name: 'SKIP_TESTS', defaultValue: false, description: '是否跳过测试')
}
stages {
stage('测试') {
when {
not { expression { params.SKIP_TESTS } }
}
steps {
sh 'dotnet test'
}
}
}
}6. Security and Permissions
6.1 Credential Management
Add credentials in Jenkins:
- Username/password
- SSH keys
- API tokens
- Docker Registry credentials
Use credentials in the pipeline:
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
Use the Role-Based Access Control (RBAC) plugin to manage user permissions:
- Install Role Strategy Plugin
- Create roles:
- Admin
- Developer
- Viewer
- Assign permissions:
- Project permissions: build, configure, delete
- System permissions: manage, configure
7. Monitoring and Alerts
7.1 Build Status Monitoring
pipeline {
agent any
stages {
// ...
}
post {
success {
slackSend channel: '#devops',
message: "构建成功: ${BUILD_URL}"
}
failure {
slackSend channel: '#devops',
message: "构建失败: ${BUILD_URL}"
}
}
}7.2 Email Notifications
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. Performance Optimization
8.1 Parallel Builds
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 Dependency Caching
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'
}
}
}
}Summary
Jenkins is a powerful CI/CD tool that can automate build, test, and deployment workflows. Proper configuration can significantly improve development efficiency and deployment quality.
Author: Lei Tao
Date: June 1, 2024