diff --git a/Dockerfile.test b/Dockerfile.test new file mode 100644 index 0000000..424eea0 --- /dev/null +++ b/Dockerfile.test @@ -0,0 +1,43 @@ +# 使用 Python 3.12 slim 镜像 +FROM python:3.12-slim + +ENV TZ=Asia/Shanghai +ENV ENV=test +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 + +# 时区 + 系统依赖 +RUN ln -sf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone \ + && rm -rf /etc/apt/sources.list.d/* \ + && echo "deb https://mirrors.aliyun.com/debian/ bookworm main non-free contrib" > /etc/apt/sources.list \ + && echo "deb https://mirrors.aliyun.com/debian-security/ bookworm-security main non-free contrib" >> /etc/apt/sources.list \ + && echo "deb https://mirrors.aliyun.com/debian/ bookworm-updates main non-free contrib" >> /etc/apt/sources.list \ + && apt-get clean \ + && apt-get update \ + && apt-get install -y --no-install-recommends curl \ + && rm -rf /var/lib/apt/lists/* + +RUN mkdir -p /app/app/logs + +WORKDIR /app + +# 先拷贝依赖声明,利用 Docker 层缓存 +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt \ + -i https://mirrors.aliyun.com/pypi/simple/ \ + --trusted-host mirrors.aliyun.com + +# 拷贝应用代码和环境配置(测试环境) +COPY app/ ./app/ +COPY .env.test ./.env.test + +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD curl -sf http://localhost:8000/health/ || exit 1 + +# Gunicorn + Uvicorn Worker +CMD ["gunicorn", "-w", "2", "-k", "uvicorn.workers.UvicornWorker", \ + "app.main:app", "-b", "0.0.0.0:8000", \ + "--timeout", "120", "--graceful-timeout", "30", \ + "--access-logfile", "-"] diff --git a/Jenkinsfile.test b/Jenkinsfile.test new file mode 100644 index 0000000..7d01ca6 --- /dev/null +++ b/Jenkinsfile.test @@ -0,0 +1,210 @@ +/** + * OfferPie Python AI 蓝绿部署流水线(测试环境) + * + * 架构:Jenkins 本地编译 → scp 镜像到目标机 → SSH 远程蓝绿切换 + * 目标机目录:/opt/offerpie/python-ai/ + * + * 与生产差异: + * - 部署目标为测试服务器 + * - 默认分支 test + * - 镜像 tag = test(与生产 latest 隔离,避免同一 Jenkins 并发构建串包) + * - tar 文件名带 tag(双保险) + * - 构建使用 Dockerfile.test(ENV=test,打入 .env.test) + */ +pipeline { + agent any + + parameters { + choice(name: 'BRANCH', choices: ['test', 'dev', 'pre', 'master'], description: '选择要部署的分支') + } + + environment { + // 目标服务器配置(测试) + DEPLOY_HOST = '8.163.131.234' + DEPLOY_PORT = '22' + DEPLOY_USER = 'root' + DEPLOY_PASS = 'Mzpy520@126.com' + + // 项目配置 + IMAGE_NAME = 'offerpie-ai' + IMAGE_TAG = 'test' + IMAGE_TAR = 'offerpie-ai-test.tar' + CONTAINER_PREFIX = 'offerpie-ai' + REMOTE_DIR = '/opt/offerpie/python-ai' + HEALTH_URL = 'http://localhost:8000/health/' + + // SSH 命令前缀 + SSH_CMD = "sshpass -p '${DEPLOY_PASS}' ssh -o StrictHostKeyChecking=no -p ${DEPLOY_PORT} ${DEPLOY_USER}@${DEPLOY_HOST}" + SCP_CMD = "sshpass -p '${DEPLOY_PASS}' scp -o StrictHostKeyChecking=no -P ${DEPLOY_PORT}" + } + + stages { + stage('环境检查') { + steps { + sh 'sshpass -V' + } + } + + stage('拉取代码') { + steps { + echo "拉取 ${params.BRANCH} 分支代码" + git branch: "${params.BRANCH}", + credentialsId: 'gitea-fab089c1-b55d-4b58-9fad', + url: 'http://git.jianshixingqiu.com/offerpai/offerpai_python_ai.git' + } + } + + stage('本地编译') { + steps { + echo "开始构建镜像" + sh "docker build -f Dockerfile.test -t ${IMAGE_NAME}:${IMAGE_TAG} ." + echo "导出镜像" + sh "docker save -o ${IMAGE_TAR} ${IMAGE_NAME}:${IMAGE_TAG}" + } + } + + stage('文件传输') { + steps { + echo "传输文件到目标服务器" + sh "${SSH_CMD} 'mkdir -p ${REMOTE_DIR}'" + sh "${SCP_CMD} ${IMAGE_TAR} ${DEPLOY_USER}@${DEPLOY_HOST}:${REMOTE_DIR}/" + sh "${SCP_CMD} nginx.conf ${DEPLOY_USER}@${DEPLOY_HOST}:${REMOTE_DIR}/nginx.conf" + sh "${SCP_CMD} docker-compose.test.yml ${DEPLOY_USER}@${DEPLOY_HOST}:${REMOTE_DIR}/docker-compose.yml" + } + } + + stage('加载镜像') { + steps { + sh "${SSH_CMD} 'docker load < ${REMOTE_DIR}/${IMAGE_TAR}'" + } + } + + stage('检测部署目标') { + steps { + script { + def blueRunning = sh(script: "${SSH_CMD} 'docker ps -q -f name=${CONTAINER_PREFIX}-blue'", returnStdout: true).trim() + def greenRunning = sh(script: "${SSH_CMD} 'docker ps -q -f name=${CONTAINER_PREFIX}-green'", returnStdout: true).trim() + + env.DEPLOY_TARGET = '' + + if (blueRunning && !greenRunning) { + env.DEPLOY_TARGET = 'green' + } + if (greenRunning && !blueRunning) { + env.DEPLOY_TARGET = 'blue' + } + if (!env.DEPLOY_TARGET) { + echo "当前环境未部署服务或状态异常,默认部署 blue" + env.DEPLOY_TARGET = 'blue' + } + + env.OTHER_TARGET = (env.DEPLOY_TARGET == 'blue') ? 'green' : 'blue' + echo "当前激活: ${env.OTHER_TARGET},即将部署: ${env.DEPLOY_TARGET}" + } + } + } + + stage('启动新版本') { + steps { + script { + def existingContainer = sh(script: "${SSH_CMD} 'docker ps -aq -f name=${CONTAINER_PREFIX}-${env.DEPLOY_TARGET}'", returnStdout: true).trim() + if (existingContainer) { + sh "${SSH_CMD} 'docker rm -f ${CONTAINER_PREFIX}-${env.DEPLOY_TARGET}'" + } + sh "${SSH_CMD} 'cd ${REMOTE_DIR} && docker compose up -d ${env.DEPLOY_TARGET}'" + sh 'sleep 15' + } + } + } + + stage('检查Nginx') { + steps { + script { + def nginxExists = sh(script: "${SSH_CMD} 'docker ps -aq -f name=${CONTAINER_PREFIX}-nginx'", returnStdout: true).trim() + if (!nginxExists) { + echo "首次部署,初始化 Nginx 容器" + sh "${SSH_CMD} 'cd ${REMOTE_DIR} && docker compose up -d nginx'" + sh 'sleep 3' + } else { + def nginxRunning = sh(script: "${SSH_CMD} 'docker ps -q -f name=${CONTAINER_PREFIX}-nginx'", returnStdout: true).trim() + if (!nginxRunning) { + echo "Nginx 容器已停止,重新启动" + sh "${SSH_CMD} 'docker start ${CONTAINER_PREFIX}-nginx'" + sh 'sleep 2' + } + echo "Nginx 容器已存在且运行中" + } + // docker cp nginx.conf 进容器 + sh "${SSH_CMD} 'docker cp ${REMOTE_DIR}/nginx.conf ${CONTAINER_PREFIX}-nginx:/etc/nginx/nginx.conf'" + } + } + } + + stage('健康检查') { + steps { + script { + def maxRetries = 3 + def retryCount = 0 + def healthy = false + + while (retryCount < maxRetries && !healthy) { + try { + sh "${SSH_CMD} 'docker exec ${CONTAINER_PREFIX}-${env.DEPLOY_TARGET} curl -f ${HEALTH_URL}'" + healthy = true + } catch (Exception e) { + retryCount++ + if (retryCount < maxRetries) { + echo "健康检查失败,5秒后重试 (${retryCount}/${maxRetries})" + sleep 5 + } + } + } + + if (!healthy) { + error "健康检查失败,部署中止" + } + echo "✅ ${CONTAINER_PREFIX}-${env.DEPLOY_TARGET} 健康检查通过" + } + } + } + + stage('切换流量') { + steps { + script { + sh "${SSH_CMD} 'docker exec ${CONTAINER_PREFIX}-nginx sed -i \"s/proxy_pass http:\\/\\/\\(blue\\|green\\):8000;/proxy_pass http:\\/\\/${env.DEPLOY_TARGET}:8000;/\" /etc/nginx/nginx.conf'" + sh "${SSH_CMD} 'docker exec ${CONTAINER_PREFIX}-nginx nginx -s reload'" + echo "✅ 流量已切换到 ${env.DEPLOY_TARGET}" + } + } + } + + stage('删除旧版本') { + steps { + script { + def otherExists = sh(script: "${SSH_CMD} 'docker ps -aq -f name=${CONTAINER_PREFIX}-${env.OTHER_TARGET}'", returnStdout: true).trim() + if (otherExists) { + sh "${SSH_CMD} 'docker rm -f ${CONTAINER_PREFIX}-${env.OTHER_TARGET}'" + echo "旧版本 ${env.OTHER_TARGET} 已删除" + } + } + } + } + + stage('清理') { + steps { + sh "${SSH_CMD} 'rm -f ${REMOTE_DIR}/${IMAGE_TAR}'" + sh "rm -f ${IMAGE_TAR}" + } + } + } + + post { + success { + echo "✅ 蓝绿部署成功!当前运行: ${env.DEPLOY_TARGET}" + } + failure { + echo '❌ 部署失败,请检查日志' + sh "rm -f ${IMAGE_TAR} || true" + } + } +} diff --git a/docker-compose.test.yml b/docker-compose.test.yml new file mode 100644 index 0000000..4717797 --- /dev/null +++ b/docker-compose.test.yml @@ -0,0 +1,65 @@ +services: + nginx: + image: nginx:alpine + container_name: offerpie-ai-nginx + restart: unless-stopped + ports: + - "10502:80" + healthcheck: + test: ["CMD", "wget", "--spider", "-q", "http://localhost/health"] + interval: 30s + timeout: 10s + retries: 3 + deploy: + resources: + limits: + memory: 256M + cpus: '1' + + blue: + image: offerpie-ai:test + container_name: offerpie-ai-blue + restart: unless-stopped + expose: + - "8000" + environment: + - APP_VERSION=blue + - ENV=test + - TZ=Asia/Shanghai + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health/"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 20s + volumes: + - /logs/offerpie-ai:/app/app/logs + deploy: + resources: + limits: + memory: 2G + cpus: '2' + + green: + image: offerpie-ai:test + container_name: offerpie-ai-green + restart: unless-stopped + expose: + - "8000" + environment: + - APP_VERSION=green + - ENV=test + - TZ=Asia/Shanghai + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health/"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 20s + volumes: + - /logs/offerpie-ai:/app/app/logs + deploy: + resources: + limits: + memory: 2G + cpus: '2'