在 Ubuntu 上打包 Go 程序时,想要减小二进制体积,可以从编译参数、系统环境、打包方式几个层面入手。下面按「实用程度」给你一套方案。
go build -ldflags="-s -w" -o app main.go
-s:去掉符号表-w:去掉 DWARF 调试信息sudo apt install upx
upx --best --lzma app
Ubuntu 默认是 glibc,体积偏大。
musl-gcc 编译sudo apt install musl-tools
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o app main.go
Go 默认就是静态链接(
CGO_ENABLED=0),不需要 glibc
FROM golang:1.22 AS build
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o app
FROM scratch
COPY --from=build /src/app /app
ENTRYPOINT ["/app"]
FROM golang:1.22-alpine AS build
RUN apk add --no-cache upx
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o app && upx --best --lzma app
FROM alpine
COPY --from=build /src/app /app
ENTRYPOINT ["/app"]
github.com/gin-gonic/gin(可选 httprouter)log/slog 而非 zap(除非必要)net/http/pprof(生产)// 不要 import _ "net/http/pprof"
| 方式 | 体积 |
|---|---|
| 默认 build | 12 MB |
-s -w |
9 MB |
| + upx | 3 MB |
| scratch 镜像 | 3 MB |
| alpine + upx | 4 MB |
CGO_ENABLED=0 go build -ldflags="-s -w" -o app
upx --best --lzma app
如果你是:
告诉我你的使用场景(CLI / 服务 / Docker),我可以给你精准配置。