在 Ubuntu 上使用 Golang 打包(编译、构建、发布)时,常见的“坑”主要分为环境相关、交叉编译、依赖与 CGO、系统差异、部署运行几类。下面按实战经验总结:
如果代码中用了:
net(部分 DNS 解析)sqlite3opencvleveldbCGO 会默认开启,编译出的二进制依赖 Ubuntu 的 glibc / 动态库。
坑:
version 'GLIBC_2.34' not found
解决:
CGO_ENABLED=0 go build
或明确指定:
CGO_ENABLED=0 GOOS=linux go build
GOOS=windows GOARCH=amd64 go build
坑:
解决:
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o app.exe
Ubuntu 老项目常见:
GOPATH 模式下编译坑:
go build 找不到包建议:
export GO111MODULE=on
go mod tidy
私有仓库:
git config --global url."git@github.com:".insteadOf "https://github.com/"
Ubuntu 下:
systemd坑:
解决:
//go:embed config.yaml
Ubuntu 常用 systemd:
[Service]
ExecStart=/opt/app/app
坑:
chmod +x app
打包后一定要:
ldd app
如果看到:
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
说明不是纯静态。
纯静态推荐:
CGO_ENABLED=0 go build -ldflags '-s -w'
Alpine 用 musl,不是 glibc
坑:
standard_init_linux.go:228: exec user process caused: no such file or directory
解决:
CGO_ENABLED=0 go build
Ubuntu apt 的 Go 很旧(1.18 以前)
坑:
建议: 从官方下:
https://go.dev/dl/
# 静态、精简、Linux
CGO_ENABLED=0 GOOS=linux go build -ldflags "-s -w" -o app
# Windows
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o app.exe
# 带版本信息
go build -ldflags "-X main.Version=1.0.0 -s -w"
Ubuntu 上 Golang 打包最大的坑:CGO + glibc + 系统差异
只要记住:
服务/容器部署 → 一律CGO_ENABLED=0
如果你有具体场景(Web / CLI / 微服务 / Docker / systemd),我可以给你更针对性的打包方案。