在 CentOS 上部署 Golang(Go)应用,通常分为「环境准备 → 编译 → 部署运行 → 进程管理 → 可选反向代理」几步。下面给你一套实用、可生产使用的做法。
# 查看最新版本
# https://go.dev/dl/
cd /usr/local
wget https://go.dev/dl/go1.22.3.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.22.3.linux-amd64.tar.gz
配置环境变量:
vim /etc/profile.d/go.sh
export PATH=$PATH:/usr/local/go/bin
export GOPATH=/root/go
export PATH=$PATH:$GOPATH/bin
生效:
source /etc/profile.d/go.sh
go version
cd your_project
go build -o app main.go
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app main.go
✅ 建议:
CGO_ENABLED=0,避免依赖系统库
scp app user@centos_ip:/opt/app/
ssh user@centos_ip
运行:
cd /opt/app
chmod +x app
./app
vim /etc/systemd/system/goapp.service
示例:
[Unit]
Description=Go App
After=network.target
[Service]
User=root
WorkingDirectory=/opt/app
ExecStart=/opt/app/app
Restart=always
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl enable goapp
systemctl start goapp
systemctl status goapp
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --reload
yum install nginx -y
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
systemctl enable nginx
systemctl start nginx
journalctl -u goapp -f
或自己写日志文件:
log.SetOutput(os.Stdout)
/opt/app/
├── app
├── config.yaml
└── logs/
本地编译
→ 上传 CentOS
→ systemd 管理
→ Nginx 反代
如果你愿意,我可以:
直接告诉我你的 Go 项目类型 即可。