在Ubuntu上部署Golang项目,可按以下步骤操作:
-
安装Go环境
sudo apt update && sudo apt install golang-go go version # 验证安装 -
准备项目代码
- 本地编写代码并初始化模块:
go mod init your_project_name - 或通过Git拉取远程代码:
git clone your_repo_url cd your_repo
- 本地编写代码并初始化模块:
-
编译项目
- 本地交叉编译(生成Linux可执行文件):
GOOS=linux GOARCH=amd64 go build -o your_app_name - 或在服务器上直接编译:
go build -o your_app_name main.go
- 本地交叉编译(生成Linux可执行文件):
-
部署到服务器
- 上传可执行文件到服务器(如用
scp):scp your_app_name user@server_ip:/path/to/destination - 服务器上赋予执行权限并运行:
chmod +x your_app_name ./your_app_name
- 上传可执行文件到服务器(如用
-
后台运行(可选)
- 使用
nohup或systemd管理进程:nohup ./your_app_name > app.log 2>&1 &或创建
systemd服务文件(如/etc/systemd/system/your_app.service)实现开机自启。
- 使用
-
优化与扩展(可选)
- 用
upx压缩二进制文件:sudo apt install upx && upx --best your_app_name - 通过Docker打包为镜像(需编写
Dockerfile):docker build -t your_app_image . docker run -d -p 8080:8080 your_app_image
- 用
说明:步骤可根据项目需求选择,生产环境建议使用systemd或Docker管理,确保服务稳定运行。