Files
index/Jenkinsfile
T

94 lines
3.3 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 -> 导出 -> 同步到 Nginx 站点目录
//
// 前置条件(见 README「自动部署(Jenkins)」):
// 1. Jenkins 用户能用 docker(通常在 docker 组里)。
// 2. 服务器预置 /usr/local/bin/index-deploy-prepare 及其 sudo 免密规则(权限自愈)。
// 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
# 1) 权限自愈:目录属主若被 1Panel 改回 root 等情况,自动修正为 jenkins
# (服务器已预置 sudo 规则,仅允许免密执行这一个脚本)
sudo -n /usr/local/bin/index-deploy-prepare
# 2) 备份当前线上版本(保留最近 10 份,便于回滚)
BK_DIR=/var/backups/index-site
mkdir -p "$BK_DIR"
if [ -n "$(ls -A "$DEPLOY_DIR" 2>/dev/null)" ]; then
tar czf "$BK_DIR/index-$(date +%Y%m%d-%H%M%S)-build${BUILD_NUMBER}.tar.gz" -C "$DEPLOY_DIR" .
ls -1t "$BK_DIR"/index-*.tar.gz | tail -n +11 | xargs -r rm -f
fi
# 3) 清空 + 发布(等价于 rsync --delete)
find "$DEPLOY_DIR" -mindepth 1 -delete
find .deploy -name .gitkeep -delete
cp -a .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'
}
}
}