在Ubuntu上快速打包Golang应用,可按以下步骤操作:
安装Go环境
sudo apt update && sudo apt install golang-go # 安装Go
go version # 验证安装
初始化项目依赖
go mod init <项目名> # 创建go.mod文件
go mod tidy # 自动管理依赖
快速编译打包
go build -o <输出文件名> # 生成可执行文件
可选:压缩文件
sudo apt install upx-ucl # 安装UPX压缩工具
upx --best <输出文件名> # 压缩可执行文件
可选:Docker打包(跨平台)
创建Dockerfile
:
FROM golang:alpine
WORKDIR /app
COPY . .
RUN go build -o <输出文件名>
CMD ["./<输出文件名>"]
构建镜像:
docker build -t <镜像名> .
说明:
CGO_ENABLED=0 GOOS=目标系统 GOARCH=架构 go build
(如GOOS=windows
生成.exe
)。CGO_ENABLED=0
)确保兼容性。