Go项目部署到Linux服务器

44 阅读2分钟

Go语言具备跨平台编译的能力,允许开发者利用Go语言自带的交叉编译工具链,轻松地将Go项目部署至Linux操作系统的服务器上。这一特性极大地简化了多平台部署的复杂性,确保了开发流程的高效性。

windows

set CGO_ENABLED=0 //禁用CGO
set GOOS=linux //目标平台为linux
set GOARCH=amd64 //目标处理器架构是amd64
go build -o name main.go //编译可执行文件到当前目录 (-o:自定义文件名)

mac

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o name main.go

通过 SSH 上传文件,并修改执行权限

一般可能没有执行权限,添加执行权限。

scp your-app user@server-ip:/path/to/destination
# 修改执行权限
chmod 777 main

运行程序

# 运行程序:
./main

# 如果需要后台运行:
nohup ./main &

程序是否成功执行

# 查看命令:
ps -aux | grep main

Nginx配置

配置Nginx作为反向代理,服务静态资源和处理请求转发。

upstream go-project {
    # go-project HTTP Server 的 IP 及 端口
    server 127.0.0.1:9501;
}

server
{
    listen 80;
    server_name goblog.com;
    
    access_log   /data/log/nginx/goblog/access.log;
    error_log    /data/log/nginx/goblog/error.log;
    
    location /static/ {
      alias /www/wwwroot/gitlab/go-project/public/uploads/; #静态资源路径
    }
    
    location / {
        # 将客户端的 Host 和 IP 信息一并转发到对应节点
        proxy_redirect             off;
        proxy_set_header           Host             $http_host;
        proxy_set_header           X-Real-IP        $remote_addr;
        proxy_set_header           X-Forwarded-For  $proxy_add_x_forwarded_for;
        
        # 转发Cookie,设置 SameSite
        proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";
        
        # 执行代理访问真实服务器
        proxy_pass                 http://go-project;
    }
    
}

创建 systemd 服务

将应用拷贝到 /usr/local/bin/ 目录

sudo cp your_app /usr/local/bin/

创建一个 systemd 服务文件 /etc/systemd/system/your_app.service

[Unit]
Description=Your Go Application
After=network.target

[Service]
ExecStart=/usr/local/bin/your_app
Restart=always
User=nobody
Group=nogroup
Environment=PORT=8080

[Install]
WantedBy=multi-user.target

启动和启用服务,这样就能实现开机自启和稳定运行 停止服务‌:sudo systemctl stop myapp ‌重启服务‌:sudo systemctl restart myapp ‌设置开机自启‌:sudo systemctl enable myapp ‌禁用开机自启‌:sudo systemctl disable myapp 查看服务状态:sudo systemctl status myapp 重新加载:sudo systemctl daemon-reload

sudo systemctl start your_app
sudo systemctl enable your_app

查看服务状态

sudo systemctl status your_app

在失败时重启

[Unit]
Description=My Go Application
After=network.target

[Service]
Type=simple
User=yourusername          ; 运行应用的用户
ExecStart=/path/to/your/go/binary ; 你的Go应用程序的启动命令
Restart=on-failure          ; 在失败时重启
RestartSec=5s               ; 重启前的等待时间

[Install]
WantedBy=multi-user.target