在开始定制打包配置前,需确保系统已安装Golang编译器及必要工具:

sudo apt update && sudo apt install -y golang-go dh-make debhelper lintiangolang-go:Debian官方提供的Golang编译器;dh-make:用于初始化Debian包结构的工具;debhelper:辅助构建Debian包的工具集;lintian:检查Debian包质量的工具。进入Golang项目根目录(包含go.mod文件),执行以下命令初始化Debian包结构:
dh_make --native -p your_project_name_version -s--native:表示本地开发包(无需上游源码);-p:指定包名及版本(格式为name_version,如myapp_1.0);-s:生成单二进制文件的简化模板(适用于大多数Golang项目)。执行后会生成debian/目录,包含control、rules、copyright等核心文件。该文件定义包的元数据,需调整以下字段:
Source: your_project_nameSection: utilsPriority: optionalMaintainer: Your Name <[email protected]>Build-Depends: debhelper-compat (= 13), golang-goStandards-Version: 4.5.1Homepage: https://github.com/your/repoPackage: your_project_nameArchitecture: amd64Depends: ${shlibs:Depends}, ${misc:Depends}, libc6 (>= 2.14)Description: A brief description of your Go application A longer description that explains the functionality and usage of your application.Build-Depends:添加golang-go作为构建依赖;Architecture:根据项目选择(amd64适用于大多数场景);Depends:指定运行时依赖(如libc6)。该文件定义构建规则,对于Golang项目,需修改为以下内容以支持go build:
#!/usr/bin/make -f%:dh $@ --buildsystem=golang --with=golang--buildsystem=golang:指定使用Golang构建系统;--with=golang:启用Golang专用构建助手。填写版权信息,格式如下:
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/Upstream-Name: your_project_nameSource: https://github.com/your/repoFiles: *Copyright: 2025 Your NameLicense: MITMIT、Apache-2.0)。在项目根目录下执行go build,生成可执行文件:
go build -o your_project_namego.mod文件已正确初始化(go mod init your_project_name)。在项目根目录下执行以下命令生成.deb包:
debuild -us -uc-us -uc:跳过签名步骤(仅用于本地测试);.deb包位于父目录(如../your_project_name_1.0_amd64.deb)。使用lintian检查生成的包是否符合Debian规范:
lintian ../your_project_name_1.0_amd64.deb若需将包部署到Docker环境,可使用多阶段构建减少镜像大小:
# 构建阶段FROM golang:1.21 AS builderWORKDIR /appCOPY . .RUN go build -o your_project_name .# 运行阶段FROM debian:bookworm-slimCOPY --from=builder /app/your_project_name /usr/local/bin/CMD ["your_project_name"]golang镜像编译项目;debian:bookworm-slim镜像运行,仅包含必要的二进制文件。通过以上步骤,可在Debian系统上完成Golang项目的定制化打包,生成符合Debian规范的.deb包,并支持后续部署或分发。