优化 Docker 工作流以支持多平台和 Go 版本构建与推送

This commit is contained in:
wood chen 2024-10-09 13:06:31 +08:00
parent 3bee688fcf
commit 77f30efde8
2 changed files with 44 additions and 31 deletions

View File

@ -1,4 +1,4 @@
name: Docker
name: Build and Push Docker Image
on:
push:
@ -13,30 +13,53 @@ env:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
go-version: [1.23.x]
platform: [linux/amd64, linux/arm64]
steps:
- name: 检出代码库
uses: actions/checkout@v3
- name: Checkout code
uses: actions/checkout@v3
- name: 构建镜像
run: docker build . --file Dockerfile --tag $IMAGE_NAME
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go-version }}
- name: 登录到镜像仓库
run: echo "${{ secrets.ACCESS_TOKEN }}" | docker login -u woodchen --password-stdin
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: 推送镜像
run: |
IMAGE_ID=woodchen/$IMAGE_NAME
IMAGE_ID=$(echo $IMAGE_ID | tr '[A-Z]' '[a-z]')
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
# 从 GitHub 事件负载中获取分支名
BRANCH_NAME=$(echo "${{ github.ref }}" | sed -e 's,.*/\(.*\),\1,')
- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: woodchen
password: ${{ secrets.ACCESS_TOKEN }}
# 对于除了 "main" 分支和标签以外的分支,使用 "latest" 版本号
VERSION=$(if [ "$BRANCH_NAME" == "main" ]; then echo "latest"; else echo $BRANCH_NAME; fi)
- name: Build Go binary
run: |
CGO_ENABLED=0 GOOS=linux GOARCH=${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }} go build -ldflags '-w -s' -o feishu_chatgpt
echo IMAGE_ID=$IMAGE_ID
echo VERSION=$VERSION
- name: Prepare Docker metadata
id: meta
uses: docker/metadata-action@v4
with:
images: woodchen/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: .
platforms: ${{ matrix.platform }}
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
docker tag $IMAGE_NAME $IMAGE_ID:$VERSION
docker push $IMAGE_ID:$VERSION

View File

@ -1,19 +1,9 @@
FROM golang:1.23 as golang
ENV GO111MODULE=on \
CGO_ENABLED=1
WORKDIR /build
ADD /code /build
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags '-w -s' -o feishu_chatgpt
FROM alpine:latest
WORKDIR /app
RUN apk add --no-cache bash
COPY --from=golang /build/feishu_chatgpt /app
COPY --from=golang /build/role_list.yaml /app
COPY feishu_chatgpt /app
COPY role_list.yaml /app
EXPOSE 9000
ENTRYPOINT ["/app/feishu_chatgpt"]