下面按从零到可运行的思路,给你讲在 CentOS 上部署 Go(Golang)应用 的常见做法,适合新手到生产环境。
在 CentOS 上部署 Go,通常有三种方式:
下面逐一说明。
如果你的程序是 已经编译好的二进制,可以跳过这一步。
cd /usr/local
wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz
vim /etc/profile
添加:
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
生效:
source /etc/profile
验证:
go version
GOOS=linux GOARCH=amd64 go build -o app main.go
然后把 app 上传到 CentOS。
go build -o app main.go
chmod +x app
./app
⚠️ 这样关闭终端就会退出,不适合生产。
vim /etc/systemd/system/myapp.service
内容示例:
[Unit]
Description=My Go App
After=network.target
[Service]
User=www
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/app
Restart=always
Environment=GO_ENV=production
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start myapp
systemctl enable myapp
systemctl status myapp
journalctl -u myapp -f
yum install nginx -y
systemctl enable nginx
systemctl start nginx
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
nginx -t
systemctl reload nginx
FROM golang:1.22 as build
WORKDIR /app
COPY . .
RUN go build -o app
FROM centos:7
WORKDIR /app
COPY --from=build /app/app .
EXPOSE 8080
CMD ["./app"]
docker build -t myapp .
docker run -d -p 8080:8080 myapp
firewall-cmd --add-port=8080/tcp --permanent
firewall-cmd --reload
netstat -tunlp | grep 8080
www)| 场景 | 推荐方式 |
|---|---|
| 学习 / 测试 | 直接运行 |
| 生产服务 | Systemd + Nginx |
| 微服务 / 容器 | Docker |
如果你愿意,可以告诉我:
我可以直接给你一套可复制的部署脚本。