113 lines
3.0 KiB
YAML
113 lines
3.0 KiB
YAML
kind: pipeline
|
||
type: docker
|
||
name: nodejs-pipeline-with-cleanup
|
||
|
||
steps:
|
||
# 步骤0:清理残留容器和镜像(优先执行)
|
||
- name: cleanup-resources
|
||
image: docker:20.10
|
||
volumes:
|
||
- name: docker-socket
|
||
path: /var/run/docker.sock
|
||
commands:
|
||
- |
|
||
# 定义应用相关的名称标识
|
||
APP_NAME="node-app"
|
||
CONTAINER_NAME="node-app-prod"
|
||
CURRENT_TAG="${DRONE_COMMIT_SHA:0:8}"
|
||
|
||
echo "开始清理残留资源..."
|
||
|
||
# 1. 停止并删除正在运行的旧容器
|
||
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
|
||
echo "停止并删除运行中的容器: $CONTAINER_NAME"
|
||
docker stop $CONTAINER_NAME || true
|
||
docker rm $CONTAINER_NAME || true
|
||
else
|
||
echo "没有运行中的 $CONTAINER_NAME 容器"
|
||
fi
|
||
|
||
# 2. 删除同前缀的旧镜像(排除当前构建标签)
|
||
echo "清理旧镜像..."
|
||
docker images --filter "reference=$APP_NAME:*" --format "{{.ID}} {{.Tag}}" | \
|
||
while read -r image_id tag; do
|
||
if [ "$tag" != "$CURRENT_TAG" ] && [ "$tag" != "<none>" ]; then
|
||
echo "删除旧镜像: $APP_NAME:$tag (IMAGE_ID: $image_id)"
|
||
docker rmi -f $image_id || true
|
||
fi
|
||
done
|
||
|
||
# 3. 清理悬空镜像(构建失败产生的none标签镜像)
|
||
echo "清理悬空镜像..."
|
||
dangling_images=$(docker images -f "dangling=true" -q)
|
||
if [ -n "$dangling_images" ]; then
|
||
docker rmi -f $dangling_images || true
|
||
else
|
||
echo "没有悬空镜像需要清理"
|
||
fi
|
||
|
||
# 步骤1:安装Node.js依赖
|
||
- name: install-dependencies
|
||
image: node:18-bullseye-slim
|
||
commands:
|
||
- npm install
|
||
volumes:
|
||
- name: node_modules
|
||
path: /app/node_modules
|
||
|
||
# 步骤2:构建Docker镜像
|
||
- name: build-app-image
|
||
image: docker:20.10
|
||
volumes:
|
||
- name: docker-socket
|
||
path: /var/run/docker.sock
|
||
- name: node_modules
|
||
path: /drone/src/node_modules
|
||
commands:
|
||
- docker build -t node-app:${DRONE_COMMIT_SHA:0:8} -f Dockerfile .
|
||
|
||
# 步骤3:测试容器运行
|
||
- name: test-container
|
||
image: docker:20.10
|
||
volumes:
|
||
- name: docker-socket
|
||
path: /var/run/docker.sock
|
||
commands:
|
||
- |
|
||
docker run --rm \
|
||
--network host \
|
||
node-app:${DRONE_COMMIT_SHA:0:8} \
|
||
sh -c "ip -V && npm start -- --version"
|
||
|
||
# 步骤4:部署容器
|
||
- name: deploy
|
||
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
|
||
|
||
volumes:
|
||
- name: node_modules
|
||
temp: {}
|
||
- name: docker-socket
|
||
host:
|
||
path: /var/run/docker.sock
|
||
|
||
trigger:
|
||
branch:
|
||
- main
|
||
- develop
|
||
event:
|
||
- push
|
||
- pull_request
|