为 Gitlab CI CD linting 制作更小的 golang docker 镜像

问题描述 投票:0回答:1

我有 golang 项目,版本为 1.21.4,并且该项目有 gitlab CI/CD linting。 我正在使用 docker runner。

stages:
  - linting

lint-vet:
  stage: linting
  tags:
    - golang-linting
  image: <MY_GOLANG_IMAGE>:latest
  script:
    - go vet ./...
  allow_failure: true
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

用于 CI/CD 的 Dockerfile:

FROM golang:1.23.3-alpine

RUN go install golang.org/x/tools/cmd/[email protected]  &&  \
    go install honnef.co/go/tools/cmd/[email protected] &&  \
    go install github.com/golangci/golangci-lint/cmd/[email protected]

这张图片的大小是963 Mb,我想重新使用它。

我尝试了两阶段建筑。

FROM golang:1.23.3-alpine as builder

RUN go install golang.org/x/tools/cmd/[email protected]  &&  \
    go install honnef.co/go/tools/cmd/[email protected] &&  \
    go install github.com/golangci/golangci-lint/cmd/[email protected]

FROM alpine:3.18.4

RUN apk add --no-cache bash go

COPY --from=builder /go/bin/goimports /usr/local/bin/
COPY --from=builder /go/bin/staticcheck /usr/local/bin/
COPY --from=builder /go/bin/golangci-lint /usr/local/bin/

但是我与项目 golang 版本发生冲突,来自 CI/CD 作业的错误:

go: errors parsing go.mod:
/builds/sub_dir/golang_linting/go.mod:3: invalid go version '1.21.4': must match format 1.23

如果我将 golang 版本设置为等于项目(和降级包),则在构建映像时会出现错误:

FROM golang:1.21.4-alpine as builder

RUN go install golang.org/x/tools/cmd/[email protected]  &&  \
    go install honnef.co/go/tools/cmd/[email protected]  &&  \
    go install github.com/golangci/golangci-lint/cmd/[email protected]

FROM alpine:3.18.4

RUN apk add --no-cache bash go=1.21.4

COPY --from=builder /go/bin/goimports /usr/local/bin/
COPY --from=builder /go/bin/staticcheck /usr/local/bin/
COPY --from=builder /go/bin/golangci-lint /usr/local/bin/

错误:

ERROR [golang-linter-ci-cd-smaller stage-1 2/5] RUN apk add --no-cache bash go=1.21.4
breaks: world[go=1.21.4]
failed to solve: process "/bin/sh -c apk add --no-cache bash go=1.21.4" did not complete successfully: exit code: 1

如何使图像变小,也许这里需要不同的方法?

docker go gitlab continuous-integration
1个回答
0
投票

没有这样的套餐,

go=1.21.4
Alpine 3.18 只有
go-1.20

根据我的经验,在构建和运行阶段使用不同的工具链是极其危险的。您使用 1.23 构建了工具,然后将它们放入 go-1.20 工具链中。呃-r-r。

我宁愿为跑步者阶段保留相同的 golang 图像:

FROM golang:1.21.4-alpine as builder

RUN go install golang.org/x/tools/cmd/[email protected]  &&  \
    go install honnef.co/go/tools/cmd/[email protected]  &&  \
    go install github.com/golangci/golangci-lint/cmd/[email protected]

FROM golang:1.21.4-alpine

COPY --from=builder /go/bin/goimports /usr/local/bin/
COPY --from=builder /go/bin/staticcheck /usr/local/bin/
COPY --from=builder /go/bin/golangci-lint /usr/local/bin/

图像大小为 281MB,比纯 222MB 多了 59MB

golang:1.21.4-alpine
。不错,国际海事组织。使用
apk add go
的图像大小为387MB。

© www.soinside.com 2019 - 2024. All rights reserved.