在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
)確保兼容性。