Golang在Linux服务器上的部署策略可根据场景选择,以下是常见方式及要点:
环境准备
PATH
和GOPATH
环境变量。wget
下载最新版本并解压至/usr/local
,避免权限问题。直接运行
GOOS=linux GOARCH=amd64 go build -o app
。chmod +x app
,通过./app
运行。nohup ./app > app.log 2>&1 &
。systemd服务
/etc/systemd/system/app.service
,配置ExecStart
、Restart
等参数。sudo systemctl daemon-reload && sudo systemctl enable --now app
。journalctl -u app
查看日志,或配置logrotate
实现日志轮转。Supervisor管理
sudo apt install supervisor
(Ubuntu)或sudo yum install supervisor
(CentOS)。/etc/supervisor/conf.d/app.conf
,指定command
、directory
等。sudo supervisorctl update && sudo supervisorctl start app
。Dockerfile
,基于golang:alpine
构建,复制二进制文件并暴露端口。FROM golang:alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o app .
FROM alpine
WORKDIR /app
COPY --from=builder /app/app .
CMD ["./app"]
docker build -t app . && docker run -d -p 8080:8080 --name app-container app
。性能调优
go build -ldflags="-s -w"
,或使用upx
压缩二进制文件。ulimit -n 65535
,或修改/etc/security/limits.conf
。安全与监控
ufw
/firewalld
)开放端口。pprof
分析性能。依赖管理