温馨提示×

golang ubuntu打包咋配置

小樊
42
2026-10-10 06:15:01
栏目: 编程语言

在 Ubuntu 上用 Golang 打包(编译)程序,通常分几种场景:本地打包、交叉编译、做成 deb 包、用 Docker 打包。下面按常见用法给你说明。


一、基础环境准备(Ubuntu)

sudo apt update
sudo apt install golang-go -y

或安装官方版本(推荐):

wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz

配置环境变量:

export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go

验证:

go version

二、普通编译(本地打包)

go build -o app main.go

或整个模块:

go build -o app .

三、交叉编译(生成其他平台可执行文件)

1️⃣ 编译 Linux 可执行文件(常见于服务器)

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app .

2️⃣ 编译 Windows

CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o app.exe .

3️⃣ 编译 macOS

CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o app .

⚠️ 如果用了 CGO(如 sqlite),需要安装对应交叉编译工具链


四、压缩体积(推荐)

go build -ldflags="-s -w" -o app .

进一步压缩:

upx app

安装 upx:

sudo apt install upx -y

五、打包成 Ubuntu deb 包(可选)

1️⃣ 安装打包工具

sudo apt install dpkg-dev -y

2️⃣ 目录结构

myapp/
├── DEBIAN
│   └── control
├── usr
│   └── local
│       └── bin
│           └── app

3️⃣ control 文件示例

Package: myapp
Version: 1.0.0
Architecture: amd64
Maintainer: you@example.com
Description: My Go App

4️⃣ 打包

dpkg-deb --build myapp

六、Docker 打包(最推荐生产用)

FROM golang:1.22 AS build
WORKDIR /app
COPY . .
RUN go build -o app .

FROM ubuntu:22.04
WORKDIR /app
COPY --from=build /app/app .
CMD ["./app"]

构建:

docker build -t myapp .

七、常见坑

❌ cannot find package
✅ go mod init xxx + go mod tidy

❌ CGO 报错
✅ CGO_ENABLED=0(纯 Go)

❌ 端口权限
✅ 用 setcap 或 nginx 反代


如果你能说具体需求(Web / CLI / 微服务 / 跨平台 / deb / Docker),我可以直接给你一套完整配置。

0 踩