建议点击 查看原文 查看最新内容。
原文链接:
https://typonotes.com/posts/2025/12/15/docker-build-platform/
标题有点拗口。
简单的说, 就是在 当前平台 中进行编译。 然后在通过 docker buildx 实现多架构镜像的创建。
好处在于:
- 类似 nodejs 这种跨平台的语言, 只需要编译一次。
- 类似 golang 这种需要交叉编译的语言, 直接之际在本平台下编译。 而不是在虚拟容器中执行。
核心要点
- 在 builder 镜像中指定编译平台
--platform=$BUILDPLATFORM - 在 runtime 镜像中供食用
$TARGETARCH 创建多架构镜像。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # language=golang
FROM --platform=$BUILDPLATFORM docker.io/library/golang:1.25.4 AS builder
WORKDIR /go/src
ADD . .
ARG VERSION
RUN VERSION=${VERSION} make build.linux
FROM docker.io/library/alpine:3.22.2 AS runtime
ARG TARGETARCH
COPY --from=builder /go/src/output/demo-app-linux-${TARGETARCH} /usr/bin/demo-app
ENV GIN_MODE=release
EXPOSE 3000
ENTRYPOINT ["/usr/bin/demo-app"]
CMD ["serve"]
|
附1 Makefile
附 golang makefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| # Makefile
VERSION ?= $(shell gitversion | jq -r '.FullSemVer')
## 获取 package
PKG = $(shell cat go.mod | grep "^module " | sed -e "s/module //g")
## 注入 version
GOBUILD=CGO_ENABLED=0 go build -buildvcs=false -a -ldflags "-X ${PKG}/version.Version=${VERSION}"
GOOS=$(shell go env GOOS)
GOARCH=$(shell go env GOARCH)
GOPATH=$(shell go env GOPATH)
build: tidy
$(GOBUILD) -o output/demo-app-$(GOOS)-$(GOARCH) ./cmd/demo-app
build.linux:
GOOS=linux GOARCH=amd64 make build
GOOS=linux GOARCH=arm64 make build
|
附2: GitVersion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # GitVersion.yml
mode: ContinuousDeployment
minor-version-bump-message: 'Release\s\d+\.\d+\.\d+'
increment: Patch
branches:
develop:
regex: ^develop$
label: 'ci'
release:
regex: ^release/.+
label: 'rc'
master:
regex: ^master$
label: ''
|