#!/bin/bash # 清理闲置资源 echo "Cleaning up unused Docker resources..." yes | docker system prune -f # 定义 Docker 镜像名称、Tag 前缀和当前时间戳 REPO_NAME="newgaokaov2" TAG_PREFIX="build_" TIMESTAMP=$(date +%Y%m%d%H%M%S) TAG="${REPO_NAME}:${TAG_PREFIX}${TIMESTAMP}" CONTAINER_NAME="${REPO_NAME}_container_${TIMESTAMP}" # 钉钉 Webhook URL DINGDING_WEBHOOK="https://oapi.dingtalk.com/robot/send?access_token=fca104958fea6273c9c7ef3f08b3d552645c214f929066785e8caf6e1885a5a6" # 输入 Git 用户名和密码(如果没有配置 Git 凭据管理器的话) GIT_USERNAME="yly" GIT_PERSONAL_ACCESS_TOKEN="53789ac2bb0ef13556e0551024f92f2872ff0918" #清理所有docker资源 #docker system prune -a --volumes # 构建 Docker 镜像并传递 Git 凭据 docker build --no-cache --build-arg GIT_USERNAME="${GIT_USERNAME}" --build-arg GIT_PERSONAL_ACCESS_TOKEN="${GIT_PERSONAL_ACCESS_TOKEN}" -t "${TAG}" . && { # 构建成功后停止并删除之前的容器 echo "Stopping and removing old containers..." docker ps -aqf "name=${REPO_NAME}_container_*" | xargs docker stop docker ps -aqf "name=${REPO_NAME}_container_*" | xargs docker rm # 删除旧的镜像(保留最新的) echo "Removing old images..." docker images --format "{{.Repository}}:{{.Tag}}" | grep "${REPO_NAME}:${TAG_PREFIX}" | grep -v "${TAG}" | xargs docker rmi # 显示成功构建的新镜像信息 echo "New image built successfully: ${TAG}" docker images | grep "${TAG}" # 启动新的容器 echo "Starting new container ${CONTAINER_NAME}..." docker run \ -p 8081:8081 \ -v /var/www/wwwroot:/app/wwwroot \ --restart unless-stopped \ --name "${CONTAINER_NAME}" \ -d "${TAG}" # 显示成功启动的容器信息 echo "Container started successfully: ${CONTAINER_NAME}" docker ps | grep "${CONTAINER_NAME}" # 钉钉消息推送 curl "$DINGDING_WEBHOOK" \ -H 'Content-Type: application/json' \ -d '{ "msgtype": "text", "text": { "content": "NewGaokao服务Docker 构建完成,镜像: '"${TAG}"' 容器: '"${CONTAINER_NAME}"' 已成功启动。" } }' echo "Notification sent to DingDing." } || { # 构建失败时显示错误信息 echo "Failed to build the Docker image." # 钉钉消息推送 curl "$DINGDING_WEBHOOK" \ -H 'Content-Type: application/json' \ -d '{ "msgtype": "text", "text": { "content": ""NewGaokao服务 Docker 构建失败,请检查错误日志。" } }' echo "Error notification sent to DingDing." }