每次运行 github 操作时,我都会遇到下载 go 模块的缓存问题。我一直在尝试在应用程序的每个构建之间存储缓存,但似乎每次在 GA 上构建时它都会下载模块。
FROM golang:1.23.2 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
ENV GOCACHE=/root/.cache/go-build
RUN --mount=type=cache,target="/root/.cache/go-build" \
CGO_ENABLED=0 GOOS=linux go build -v -o main ./src/
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /app
COPY --from=builder /app/main .
CMD ["./main"]
name: Build and Deploy
on:
push:
branches:
- 'main'
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23.2"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
version: latest
driver-opts: |
image=moby/buildkit:latest
- name: Login to Github container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: docker/Dockerfile
push: true
tags: |
ghcr.io/org/app:latest
ghcr.io/org/app:${{ github.sha }}
platforms: linux/amd64
cache-from: type=registry,ref=ghcr.io/org/app:latest
cache-to: type=inline
deploy:
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
if: "!contains(github.event.head_commit.message, '[skip deploy]')"
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Deploy to Server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_KEY }}
script_stop: true
script: |
cd /path/to/app/docker
git pull origin main
echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin
docker compose down --remove-orphans
docker network prune -f
docker compose pull
docker compose up -d
我真的很困惑为什么我的构建没有缓存模块。我已经尝试了很多不同的事情,但似乎无法缩短应用程序任何后续构建的构建时间。
我预计后续构建的时间会大大缩短,这样它就不会重新获取和下载我的 GO 应用程序的所有模块。我尝试了几种不同的缓存策略,没有改变它。如果我做错了,我真的很感激一些指导。
您是否尝试过将
cache-dependency-path
添加到 Set up Go
步骤中?比如:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23.2"
cache-dependency-path: <path to go.sum>