第一步:GO部署及环境配置
1、下载 Go: 访问 Go 官方下载页面,选择最新的 Linux 版本。例如:
# 检查最新版本,替换下面的文件名
wget https://go.dev/dl/go1.21.3.linux-amd64.tar.gz
2、解压 Go:
# 删除旧的(如果有)
sudo rm -rf /usr/local/go
# 解压到 /usr/local
sudo tar -C /usr/local -xzf go1.21.3.linux-amd64.tar.gz
3、配置环境变量: 编辑您的 ~/.bashrc 或 ~/.profile 文件:
nano ~/.bashrc
在文件末尾添加:
export PATH=$PATH:/usr/local/go/bin
使其生效:
source ~/.bashrc
4、验证安装:
go version
# 应输出类似: go version go1.21.3 linux/amd64
第二步:准备和编译代码
1、创建项目目录:
mkdir ~/auth-service
cd ~/auth-service
2、初始化 Go 模块:
go mod init auth-service
3、创建 Go 代码文件: 使用 nano main.go 创建文件,然后将下面完整的代码粘贴进去。
package main
import (
"crypto/md5"
"encoding/base64"
...
4、下载依赖:
go mod tidy
# 这会自动下载 github.com/gin-gonic/gin
5、编译:
# -ldflags "-s -w" 是可选的,它会减小编译后的文件大小
# CGO_ENABLED=0 确保静态编译,不依赖C库
CGO_ENABLED=0 GOOS=linux go build -a -ldflags "-s -w" -o auth-service main.go
执行完毕后,您会得到一个名为 auth-service 的可执行文件。
第三步:运行和持久化部署
1、测试运行: 您可以先在前台运行测试一下:
./auth-service
# 应输出: Starting auth service on :8080
2、使用 systemd 持久化运行 (推荐): 为了让服务在后台运行,并在服务器重启后自动启动,我们使用 systemd。
1)创建 systemd 服务文件:
sudo nano /etc/systemd/system/auth-service.service
2)粘贴以下内容: (重要: User 和 ExecStart 中的路径需要根据您的实际情况修改:
[Unit]
Description=Go Authentication Service
After=network.target
[Service]
# 替换为您运行此服务的用户名 (例如 www-data 或您的用户名)
User=root
# 替换为您的 auth-service 文件的绝对路径
ExecStart=/root/auth-service/auth-service
# 替换为您的工作目录
WorkingDirectory=/root/auth-service
Restart=always
RestartSec=3
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
3、启动服务:
sudo systemctl daemon-reload # 重新加载配置
sudo systemctl enable auth-service # 设置开机自启
sudo systemctl start auth-service # 立即启动
4、检查服务状态:
sudo systemctl status auth-service
应该能看到它显示 active (running)。
最后:
如果修改了main.go文件,需要重新编译,并且重启服务:
CGO_ENABLED=0 GOOS=linux go build -a -ldflags "-s -w" -o auth-service main.go
sudo systemctl restart auth-service
sudo systemctl status auth-service