Debian 下简化 Golang 打包的实用方案
一、推荐路径 dh-golang 最小化流程
- 安装工具链:sudo apt-get install dh-golang golang-go(或 golang-any)、debhelper。
- 准备模块:确保项目根目录有 go.mod,执行 go mod tidy,必要时设置代理:go env -w GOPROXY=https://goproxy.cn,direct。
- 生成打包骨架:在项目根目录执行 dh_make -f …/your-project_1.0.0.orig.tar.gz(或 dh_make 交互式),选择单二进制包模板。
- 关键文件最简配置:
- debian/control(要点)
- Build-Depends: debhelper (>= 10), dh-golang, golang-go
- Standards-Version: 4.5.0
- debian/rules(最简示例,使用 dh-golang 自动探测)
- #!/usr/bin/make -f
%:
dh $@ --buildsystem=golang --with=golang
- debian/install(可选,安装二进制与资源)
- your-go-app /usr/bin/
- config.toml /etc/your-go-app/
- static/ /usr/share/your-go-app/static/
- 构建与检查:debuild -us -uc 或 dpkg-buildpackage -us -uc -b;完成后用 lintian 检查并按需修正。
- 说明:dh-golang 能自动处理 Go 模块依赖与安装,显著简化 debian/rules 与构建流程,是当前对 gc 编译器最省心的路径。
二、极简“预编译二进制”直打包(绕过构建与 lintian)
- 适用场景:你已在 CI/本地完成交叉编译,只想把二进制封装为 .deb。
- 步骤:
- 准备目录结构:mkdir -p your-app-1.0.0/DEBIAN
- 写入 debian/control(示例)
- Package: your-go-app
Version: 1.0.0
Architecture: amd64
Maintainer: Your Name you@example.com
Description: A simple Go app
- 放入二进制与资源:将可执行文件放到 your-app-1.0.0/usr/bin/,其他资源按目标路径放置。
- 构建:dpkg-deb --build your-app-1.0.0
- 安装与验证:sudo dpkg -i your-app-1.0.0.deb && your-go-app --version
- 提示:若仍使用 debuild 但想跳过 lintian,可用 dpkg-buildpackage -us -uc -b;若希望保留 debuild 流程又忽略特定告警,可在 debian/ 下配置 lintian-overrides/ 文件。该方式最快速,但偏离“从源码构建”的 Debian 常规做法。
三、常见坑与优化要点
- 静态链接与 lintian:Go 二进制常为静态链接,可能触发如缺少手册页、未启用 RELRO 等告警;优先用 dh-golang 的规范方式,必要时使用 lintian-overrides 精确忽略,而非全局关闭检查。
- 依赖与代理:非标准模块或国内网络建议在打包前设置 GOPROXY=https://goproxy.cn,direct,并 go mod tidy,减少构建不确定性。
- 包内容最小化:只打包必要的二进制与资源,避免把整个模块缓存或源码打进 .deb;完善 debian/copyright 与许可证信息,便于合规分发。
- 构建与安装分离:若采用“预编译直打包”,务必在 CI 中固定 GOOS/GOARCH 与版本,确保产物可复现与可验证。