kind: pipeline type: docker name: nodejs-host-network-pipeline steps: # 步骤0:清理残留容器和镜像(优先执行) - name: cleanup-resources image: docker:20.10 volumes: - name: docker-socket path: /var/run/docker.sock environment: APP_NAME: from_secret: app_name CONTAINER_NAME: from_secret: container_name commands: # 直接在命令中设置变量,避免shell解释器问题 - CURRENT_TAG=$(echo ${DRONE_COMMIT_SHA} | cut -c1-8) # - echo "APP_NAME=$APP_NAME, CONTAINER_NAME=$CONTAINER_NAME, CURRENT_TAG=$CURRENT_TAG" - echo $APP_NAME - echo $CONTAINER_NAME - echo $CURRENT_TAG - echo "开始清理残留资源..." # 1. 停止并删除正在运行的旧容器 # 使用默认值作为最后的保障 - | SAFE_CONTAINER_NAME=${CONTAINER_NAME:-"node-app-prod-default"} if [ "$(docker ps -q -f name=${SAFE_CONTAINER_NAME})" ]; then echo "停止并删除运行中的容器: ${SAFE_CONTAINER_NAME}" docker stop "${SAFE_CONTAINER_NAME}" || true docker rm "${SAFE_CONTAINER_NAME}" || true else echo "没有运行中的 ${SAFE_CONTAINER_NAME} 容器" fi # 2. 删除同前缀的旧镜像(排除当前构建标签) - | SAFE_APP_NAME=${APPNAME:-"node-app-default"} SAFE_CURRENT_TAG=${CURRENT_TAG:-"unknown"} echo "清理旧镜像..." docker images --filter "reference=${SAFE_APP_NAME}:*" --format "{{.ID}} {{.Tag}}" | \ while read -r image_id tag; do if [ "$tag" != "$SAFE_CURRENT_TAG" ] && [ "$tag" != "" ]; then echo "删除旧镜像: ${SAFE_APP_NAME}:${tag} (ID: ${image_id})" docker rmi -f ${image_id} || true fi done # 3. 清理悬空镜像 - | echo "清理悬空镜像..." dangling_images=$(docker images -f "dangling=true" -q) if [ -n "$dangling_images" ]; then docker rmi -f $dangling_images || true else echo "没有悬空镜像需要清理" fi # 第一步:准备环境并安装依赖 - name: install-dependencies image: node:18-bullseye commands: # 安装iproute2工具 - apt-get update && apt-get install -y iproute2 # 验证ip命令是否可用 - ip -V # 安装项目依赖 - npm install volumes: - name: node_modules path: /app/node_modules # 第三步:构建Docker镜像 - name: build-image image: docker:20.10 volumes: - name: docker-socket path: /var/run/docker.sock - name: node_modules path: /app/node_modules commands: - docker build -t node-app:${DRONE_COMMIT_SHA:0:8} -f Dockerfile . # 第四步:使用host网络运行应用 - name: run-with-host-network image: docker:20.10 volumes: - name: docker-socket path: /var/run/docker.sock commands: - | docker run -d \ --restart always \ --network host \ --name node-app-prod \ node-app:${DRONE_COMMIT_SHA:0:8} when: branch: - main # 定义卷用于共享依赖和Docker socket volumes: - name: node_modules temp: {} - name: docker-socket host: path: /var/run/docker.sock # 构建触发条件 trigger: branch: - main - develop event: - push - pull_request