Files
index/Jenkinsfile
T

80 lines
2.6 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.
// =============================================================================
// Jenkins 声明式流水线(容器化构建)
// 流程:Gitea push -> 检出 -> docker 构建 dist -> 导出 -> rsync 到 Nginx 站点目录
//
// 前置条件(见 README「自动部署(Jenkins)」):
// 1. Jenkins 用户能用 docker(通常在 docker 组里)。
// 2. jenkins 用户对 DEPLOY_DIR 有写权限。
// 3. Job 的 SCM 指向本仓库,并开启 Gitea push 触发 + 配置 Gitea webhook。
// 说明:构建跑在 node:22-alpine 容器里,宿主机 Jenkins 不需要安装 Node。
// =============================================================================
pipeline {
agent any
options {
timestamps()
disableConcurrentBuilds() // 避免两次部署互相覆盖
buildDiscarder(logRotator(numToKeepStr: '20'))
skipDefaultCheckout(true) // 用下面的显式 checkout
}
environment {
// Nginx 站点根目录(1Panel 管理)。换站点只改这里。
DEPLOY_DIR = '/opt/1panel/www/sites/xiaozhou233.cn/index'
IMAGE_NAME = 'xiaozhou-index-build'
}
stages {
stage('Checkout') {
steps {
cleanWs()
checkout scm
}
}
stage('Build (Docker)') {
steps {
sh '''
set -euo pipefail
IMAGE="${IMAGE_NAME}:latest"
# 只在容器内构建,得到 /app/dist;不产生运行镜像
# 固定 tag:新构建会顶掉旧 tag,旧的变成悬空镜像,由 post 里的 prune 清理
docker build --target build -t "$IMAGE" .
# 把 dist 导出到工作区(docker cp 出来的文件属主是 jenkins,便于后续 rsync)
rm -rf .deploy && mkdir -p .deploy
cid=$(docker create "$IMAGE")
docker cp "$cid:/app/dist/." .deploy/
docker rm "$cid" >/dev/null
echo "--- 构建产物 ---"
ls -la .deploy
'''
}
}
stage('Deploy') {
steps {
sh '''
set -euo pipefail
mkdir -p "$DEPLOY_DIR"
# 增量同步;--delete 清掉上次的旧哈希文件;排除 extra/ 带来的占位文件
rsync -az --delete --exclude='.gitkeep' .deploy/ "$DEPLOY_DIR"/
echo "✅ Deployed to $DEPLOY_DIR"
'''
}
}
}
post {
success {
echo "部署成功:${env.DEPLOY_DIR}"
}
failure {
echo '构建或部署失败,请查看上方日志'
}
always {
// 清理本次构建产生的悬空镜像,避免磁盘膨胀
sh 'docker image prune -f >/dev/null 2>&1 || true'
}
}
}