Skip to content

Build and Push Docker Image #1947

Build and Push Docker Image

Build and Push Docker Image #1947

name: 自动构建与发布
on:
# 1. 定时触发:每小时检查一次
schedule:
- cron: '0 * * * *'
# 2. 发布触发:当你在 GitHub 页面点击 "Publish release" 时触发
# 这比单纯的 push tags 更正式,适合你写版本公告
release:
types: [published]
# 3. 手动触发
workflow_dispatch:
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: 检出代码
uses: actions/checkout@v4
with:
fetch-depth: 0
# --- 智能检查逻辑 ---
- name: 检查是否需要构建
id: check
run: |
# 默认为 true (发布新版本或手动触发时,必须构建)
echo "should_build=true" >> $GITHUB_OUTPUT
# 只有在【定时任务】时,才检查代码是否有更新
if [ "${{ github.event_name }}" == "schedule" ]; then
LAST_COMMIT=$(git log -1 --format=%ct)
NOW=$(date +%s)
DIFF=$((NOW - LAST_COMMIT))
# 检查过去 65 分钟内是否有代码提交
if [ "$DIFF" -gt 3900 ]; then
echo "No changes detected in the last hour."
echo "should_build=false" >> $GITHUB_OUTPUT
fi
fi
- name: 配置 QEMU (多架构支持)
if: steps.check.outputs.should_build == 'true'
uses: docker/setup-qemu-action@v3
- name: 配置 Docker Buildx
if: steps.check.outputs.should_build == 'true'
uses: docker/setup-buildx-action@v3
- name: 登录 GHCR
if: steps.check.outputs.should_build == 'true'
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# --- 核心:标签管理 (已按你的要求简化) ---
- name: 生成 Docker 标签
if: steps.check.outputs.should_build == 'true'
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
# 这里的逻辑是自动化的:
# 1. 如果是定时任务 (schedule),只会生成 :latest
# 2. 如果是发布版本 (release v1.0),会生成 :1.0 和 :latest
tags: |
type=raw,value=latest
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: 构建并推送
if: steps.check.outputs.should_build == 'true'
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
pull: true
# 引用上面生成的标签
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
# 自动构建 amd64 和 arm64,生成统一的 Manifest
platforms: linux/amd64,linux/arm64
cache-from: type=gha
cache-to: type=gha,mode=max