writeOff/Jenkinsfile
haomingming b91077eda6 jenkins
2026-06-16 10:47:42 +08:00

97 lines
4.1 KiB
Groovy
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

pipeline {
// 可以在这里指定运行的节点any 表示任何可用的 Jenkins 节点
agent any
environment {
// 定义镜像名称和标签
DOCKER_REGISTRY = '' // 如果有私有仓库,填在这里,如 'registry.cn-hangzhou.aliyuncs.com/my-ns/'
FRONTEND_IMAGE_NAME = 'writeoff-frontend'
BACKEND_IMAGE_NAME = 'writeoff-backend'
IMAGE_TAG = "${env.BUILD_NUMBER}" // 或者用 git commit hash
// 部署的目标服务器目录
DEPLOY_DIR = '/opt/writeoff'
}
stages {
// ---------------------------------------------------------
// 后端构建阶段
// ---------------------------------------------------------
stage('Build Backend') {
when {
// 仅当 backend 目录下的文件或 Dockerfile 发生变化时执行
changeset "backend/**"
}
steps {
echo "=============================="
echo "🚀 检测到后端代码变更,开始构建后端镜像..."
echo "=============================="
dir('backend') {
// 使用 Docker 构建后端镜像
sh "docker build -t ${DOCKER_REGISTRY}${BACKEND_IMAGE_NAME}:${IMAGE_TAG} ."
sh "docker tag ${DOCKER_REGISTRY}${BACKEND_IMAGE_NAME}:${IMAGE_TAG} ${DOCKER_REGISTRY}${BACKEND_IMAGE_NAME}:latest"
// 如果有私有仓库,可以在这里 push
// sh "docker push ${DOCKER_REGISTRY}${BACKEND_IMAGE_NAME}:${IMAGE_TAG}"
// sh "docker push ${DOCKER_REGISTRY}${BACKEND_IMAGE_NAME}:latest"
}
}
}
// ---------------------------------------------------------
// 前端构建与部署阶段 (方案1: 直接打包并复制静态文件)
// ---------------------------------------------------------
stage('Build & Deploy Frontend') {
when {
// 仅当 frontend 目录下的文件发生变化时执行
changeset "frontend/**"
}
steps {
echo "=============================="
echo "🚀 检测到前端代码变更,开始构建前端..."
echo "=============================="
dir('frontend') {
// 使用 npm 安装依赖并构建
sh "npm install"
sh "npm run build"
// 将打包好的静态文件复制到目标服务器的 Nginx 目录
// TODO: 请将 root@your-server:/usr/share/nginx/html/ 替换为实际部署路径
echo "📦 部署前端静态文件(dist)到 Nginx 目录..."
sh "scp -r dist/* root@your-server:/usr/share/nginx/html/"
}
}
}
// ---------------------------------------------------------
// 部署阶段 (使用 Docker Compose)
// ---------------------------------------------------------
stage('Deploy') {
steps {
echo "=============================="
echo "📦 开始部署项目..."
echo "=============================="
// 这里假设您是在 Jenkins 本机运行 docker-compose或者通过 SSH 连到目标服务器执行
// 示例中我们直接通过 docker-compose up -d 更新服务
sh "docker-compose up -d"
// 清理悬空镜像(可选项,防止磁盘占用过大)
sh "docker image prune -f"
}
}
}
// ---------------------------------------------------------
// 构建后处理
// ---------------------------------------------------------
post {
success {
echo "✅ 构建和部署成功!"
}
failure {
echo "❌ 构建或部署失败,请检查 Jenkins 日志。"
}
}
}