在 Debian 上部署 Golang 服务,通常分为 安装 Go、构建程序、运行服务、设为开机自启 几个步骤。下面给你一套生产环境常用方案。
sudo apt update
sudo apt install -y wget
cd /tmp
wget https://go.dev/dl/go1.22.5.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.22.5.linux-amd64.tar.gz
配置环境变量:
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc
验证:
go version
在你的项目目录:
cd myapp
go build -o myapp main.go
(建议生产环境加参数)
go build -ldflags="-s -w" -o myapp
sudo mkdir -p /opt/myapp
sudo cp myapp /opt/myapp/
sudo cp -r config /opt/myapp/
sudo nano /etc/systemd/system/myapp.service
示例:
[Unit]
Description=Golang App
After=network.target
[Service]
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/myapp
Restart=always
Environment=GO_ENV=production
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp
journalctl -u myapp -f
sudo apt install nginx
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
}
}
sudo nginx -t
sudo systemctl reload nginx
sudo ufw allow 80
sudo ufw allow 443
| 方式 | 适合场景 |
|---|---|
| systemd | 单机服务(最常用) |
| Docker | 微服务 / CI |
| supervisor | 老系统 |
| k8s | 大规模 |
如果你愿意,我可以:
你现在的 Go 服务是 Web 服务还是定时任务?