topfans/backend/docs/服务器部署指南.md
2026-04-17 17:17:32 +08:00

806 lines
18 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# TopFans 后端服务器部署指南
本指南适用于在全新的 Linux 服务器上从零开始部署 TopFans 后端项目。
## 目录
- [系统要求](#系统要求)
- [第一步:服务器基础环境配置](#第一步服务器基础环境配置)
- [第二步:安装 Go 环境](#第二步安装-go-环境)
- [第三步:安装 PostgreSQL 数据库](#第三步安装-postgresql-数据库)
- [第四步:安装 Protobuf 编译器](#第四步安装-protobuf-编译器)
- [第五步:部署后端代码](#第五步部署后端代码)
- [第六步:配置环境变量](#第六步配置环境变量)
- [第七步:编译并安装二进制文件](#第七步编译并安装二进制文件)
- [第八步配置进程守护systemd](#第八步配置进程守护systemd)
- [第九步:启动与验证](#第九步启动与验证)
- [更新部署](#更新部署)
- [故障排查](#故障排查)
- [性能优化建议](#性能优化建议)
- [多机部署说明](#多机部署说明)
---
## 系统要求
### 硬件要求
- **CPU**: 2 核及以上
- **内存**: 4 GB 及以上(推荐 8 GB
- **磁盘**: 20 GB 及以上可用空间
- **网络**: 稳定的互联网连接
### 操作系统
- Ubuntu 20.04 LTS / 22.04 LTS推荐
- CentOS 7 / 8
- Debian 10 / 11
### 服务端口
| 服务 | 端口 | 协议 |
|---|---|---|
| GatewayHTTP REST API| 8080 | HTTP |
| User Service | 20000 | Dubbo/Triple |
| Gallery Service | 20001 | Dubbo/Triple |
| Social Service | 20002 | Dubbo/Triple |
| Asset Service | 20003 | Dubbo/Triple |
| Activity Service | 20004 | Dubbo/Triple |
| PostgreSQL | 5432 | TCP仅内网访问 |
---
## 第一步:服务器基础环境配置
```
ssh root@101.132.250.62
R251Y>Y8inL_BM=W
```
### 1.1 更新系统包
```bash
# Ubuntu/Debian
sudo apt update && sudo apt upgrade -y
# CentOS/RHEL
sudo yum update -y
```
### 1.2 安装基础工具
```bash
# Ubuntu/Debian
sudo apt install -y git curl wget vim build-essential unzip
# CentOS/RHEL
sudo yum install -y git curl wget vim gcc gcc-c++ make unzip
```
### 1.3 配置防火墙
```bash
# Ubuntu/Debianufw
sudo ufw allow 8080/tcp
sudo ufw allow 20000:20004/tcp
sudo ufw enable
# CentOS/RHELfirewalld
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --permanent --add-port=20000-20004/tcp
sudo firewall-cmd --reload
```
> **安全提示**: 5432 端口PostgreSQL不应对公网开放仅允许服务器本机访问。
---
## 第二步:安装 Go 环境
### 2.1 下载并安装 Go
```bash
cd /tmp
wget https://go.dev/dl/go1.25.6.linux-amd64.tar.gz
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.25.6.linux-amd64.tar.gz
rm go1.25.6.linux-amd64.tar.gz
```
### 2.2 配置环境变量
```bash
vim ~/.bashrc
# 在文件末尾添加:
export PATH=$PATH:/usr/local/go/bin
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
export GOPROXY=https://goproxy.cn,direct
export GO111MODULE=on
source ~/.bashrc
```
### 2.3 验证安装
```bash
go version
# 预期输出: go version go1.25.6 linux/amd64
```
---
## 第三步:安装 PostgreSQL 数据库
### 3.1 安装 PostgreSQL
```bash
# Ubuntu/Debian
sudo apt install -y postgresql postgresql-contrib
sudo systemctl start postgresql
sudo systemctl enable postgresql
# CentOS/RHEL
sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo yum install -y postgresql14-server postgresql14-contrib
sudo /usr/pgsql-14/bin/postgresql-14-setup initdb
sudo systemctl start postgresql-14
sudo systemctl enable postgresql-14
```
### 3.2 创建数据库和用户
```bash
sudo -u postgres psql
```
```sql
-- 创建数据库
CREATE DATABASE "top-fans";
-- 创建用户(与 common.env 中 DB_USER / DB_PASSWORD 保持一致)
CREATE USER topfans_user WITH PASSWORD 'your_secure_password_here';
-- 授予权限
GRANT ALL PRIVILEGES ON DATABASE "top-fans" TO topfans_user;
\q
```
### 3.3 验证连接
```bash
psql -h localhost -U topfans_user -d top-fans
psql -h localhost -U haihuizhu -d top-fans
密码Z^Bz8kbH.h~mMZ~!
# 输入密码后能成功连接即代表配置正确
```
---
## 第四步:安装 Protobuf 编译器
### 4.1 安装 protoc
```bash
# Ubuntu/Debian
sudo apt install -y protobuf-compiler
# 或手动安装最新版CentOS 或需要特定版本时)
cd /tmp
wget https://github.com/protocolbuffers/protobuf/releases/download/v27.2/protoc-27.2-linux-x86_64.zip
sudo unzip protoc-27.2-linux-x86_64.zip -d /usr/local
rm protoc-27.2-linux-x86_64.zip
protoc --version
```
### 4.2 安装 Go protoc 插件
```bash
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install github.com/dubbogo/protoc-gen-go-triple/v3@latest
which protoc-gen-go
which protoc-gen-go-triple
```
---
## 第五步:部署后端代码
### 5.1 创建部署目录
```bash
# 二进制文件统一存放于 /opt/topfans
sudo mkdir -p /opt/topfans
sudo chown root:root /opt/topfans
# 配置文件存放于 /etc/topfans
sudo mkdir -p /etc/topfans
sudo chown root:root /etc/topfans
sudo chmod 750 /etc/topfans
```
### 5.2 克隆代码仓库
```bash
mkdir -p ~/projects
cd ~/projects
git clone https://github.com/your-org/TopFans.git
cd TopFans/backend
```
### 5.3 下载 Go 依赖
项目使用 Go Workspace`go.work`),各模块独立管理依赖,需在每个模块目录下分别执行:
```bash
BASE=~/projects/TopFans/backend
# 主模块(共享 pkg
cd $BASE && go mod download
# Gateway
cd $BASE/gateway && go mod download
# 各 Service
for svc in userService socialService galleryService assetService activityService; do
cd $BASE/services/$svc && go mod download
done
```
---
## 第六步配置环境变量模板配置在deploy文件夹中
项目采用**分层环境变量**策略:公共配置一份,各服务私有配置一份,部署时分别写入 `/etc/topfans/`
### 6.1 公共配置(所有服务共享)
```bash
sudo vim /etc/topfans/common.env
```
```ini
# ==================== 公共配置 ====================
ENV=production
LOG_LEVEL=info
# PostgreSQL 连接(多机部署时改为数据库服务器 IP
DB_HOST=localhost
DB_PORT=5432
DB_USER=haihuizhu
DB_PASSWORD=Z^Bz8kbH.h~mMZ~!
DB_NAME=top-fans
```
### 6.2 各服务私有配置
#### User Service
```bash
sudo vim /etc/topfans/user.env
```
```ini
PORT=20000
```
#### Gallery Service
```bash
sudo vim /etc/topfans/gallery.env
```
```ini
PORT=20001
USER_SERVICE_URL=tri://localhost:20000
ASSET_SERVICE_URL=tri://localhost:20003
```
#### Social Service
```bash
sudo vim /etc/topfans/social.env
```
```ini
PORT=20002
USER_SERVICE_URL=tri://localhost:20000
ASSET_SERVICE_URL=tri://localhost:20003
```
#### Asset Service
```bash
sudo vim /etc/topfans/asset.env
```
```ini
PORT=20003
USER_SERVICE_URL=tri://localhost:20000
# 阿里云 OSS替换为真实值
OSS_REGION=cn-shanghai
OSS_BUCKET_NAME=top-fans-test
OSS_ACCESS_KEY_ID=LTAI5tNaAjTNiHnefMCG3q4J
OSS_ACCESS_KEY_SECRET=48wwZvNkUn1PO1xWjV4HuE5JjB6G7c
OSS_ROLE_ARN=acs:ram::1387642798143585:role/top-fans-oss-user
```
#### Activity Service
```bash
sudo vim /etc/topfans/activity.env
```
```ini
# ==================== Activity Service 私有配置 ====================
# 多机部署时将此文件放到 activity 服务器的 /etc/topfans/activity.env
# 服务端口
PORT=20004
# 下游服务地址多机部署时改为对应服务器内网IP
USER_SERVICE_URL=tri://localhost:20000
GALLERY_SERVICE_URL=tri://localhost:20001
```
#### Gateway
```bash
sudo vim /etc/topfans/gateway.env
```
```ini
GIN_MODE=release
SERVER_PORT=8080
# JWT 密钥(生产环境务必替换为随机强密码)
JWT_SECRET=your_secure_jwt_secret_here
# 下游服务地址(多机部署时改为对应服务器内网 IP
DUBBO_USER_SERVICE_URL=tri://localhost:20000
DUBBO_GALLERY_SERVICE_URL=tri://localhost:20001
DUBBO_SOCIAL_SERVICE_URL=tri://localhost:20002
DUBBO_ASSET_SERVICE_URL=tri://localhost:20003
DUBBO_ACTIVITY_SERVICE_URL=tri://localhost:20004
```
### 6.3 保护配置文件权限
```bash
# 仅允许 topfans 用户读取
sudo chmod 640 /etc/topfans/*.env
sudo chown root:root /etc/topfans/*.env
```
---
## 第七步:编译并安装二进制文件
### 7.1 编译 Proto 文件(如有 .proto 变更)
```bash
cd ~/projects/TopFans/backend
bash scripts/compile-proto.sh
# 验证生成结果
ls pkg/proto/*/
```
### 7.2 编译所有服务
```bash
BASE=~/projects/TopFans/backend
# Gateway
cd $BASE/gateway
go build -ldflags="-s -w" -o /opt/topfans/gateway .
# User Service
cd $BASE/services/userService
go build -ldflags="-s -w" -o /opt/topfans/user-service .
# Gallery Service
cd $BASE/services/galleryService
go build -ldflags="-s -w" -o /opt/topfans/gallery-service .
# Social Service
cd $BASE/services/socialService
go build -ldflags="-s -w" -o /opt/topfans/social-service .
# Asset Service
cd $BASE/services/assetService
go build -ldflags="-s -w" -o /opt/topfans/asset-service .
# Activity Service
cd $BASE/services/activityService
go build -ldflags="-s -w" -o /opt/topfans/activity-service .
```
### 7.3 验证二进制文件
```bash
ls -lh /opt/topfans/
# 预期看到 6 个可执行文件:
# gateway user-service gallery-service social-service asset-service activity-service
```
---
## 第八步配置进程守护systemd
`deploy/systemd/` 目录下已提供所有服务的 systemd 模板,直接复制后启用即可。
### 8.1 安装 systemd 服务文件
```bash
BASE=~/projects/TopFans/backend
sudo cp $BASE/deploy/systemd/topfans-user.service /etc/systemd/system/
sudo cp $BASE/deploy/systemd/topfans-gallery.service /etc/systemd/system/
sudo cp $BASE/deploy/systemd/topfans-social.service /etc/systemd/system/
sudo cp $BASE/deploy/systemd/topfans-asset.service /etc/systemd/system/
sudo cp $BASE/deploy/systemd/topfans-activity.service /etc/systemd/system/
sudo cp $BASE/deploy/systemd/topfans-gateway.service /etc/systemd/system/
```
每个服务文件的核心内容如下(以 User Service 为例):
```ini
[Unit]
Description=TopFans User Service
After=network.target postgresql.service
[Service]
User=topfans
WorkingDirectory=/opt/topfans
EnvironmentFile=/etc/topfans/common.env
EnvironmentFile=/etc/topfans/user.env
ExecStart=/opt/topfans/user-service
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
```
> **说明**: `ExecStart` 只指定二进制路径,不传任何 flag。服务启动时自动读取 `EnvironmentFile` 中的环境变量作为 flag 默认值优先级CLI flag > ENV > 硬编码默认值)。
### 8.2 重载并启用所有服务
```bash
sudo systemctl daemon-reload
# 设置开机自启
sudo systemctl enable topfans-user topfans-gallery topfans-social \
topfans-asset topfans-activity topfans-gateway
```
---
## 第九步:启动与验证
### 9.1 按依赖顺序启动服务
```bash
# 1. 先启动无依赖的基础服务
sudo systemctl start topfans-user
sudo systemctl start topfans-asset
# 2. 启动依赖基础服务的上层服务
sudo systemctl start topfans-gallery
sudo systemctl start topfans-social
sudo systemctl start topfans-activity
# 3. 最后启动 Gateway
sudo systemctl start topfans-gateway
```
### 9.2 验证服务状态
```bash
# 查看所有服务状态
sudo systemctl status topfans-user topfans-gallery topfans-social \
topfans-asset topfans-activity topfans-gateway
# 检查端口监听
ss -tlnp | grep -E '8080|2000[0-4]'
```
### 9.3 测试 API
```bash
# 健康检查Gateway
curl -i http://localhost:8080/health
# 测试登录接口
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"test","password":"test"}'
```
### 9.4 查看日志
```bash
# 实时跟踪单个服务日志
sudo journalctl -u topfans-gateway -f
# 查看最近 100 行
sudo journalctl -u topfans-user -n 100
# 同时查看多个服务日志
sudo journalctl -u topfans-user -u topfans-social -f
```
---
## 更新部署
```bash
BASE=~/projects/TopFans/backend
# 1. 拉取最新代码
cd $BASE && git pull origin main
# 2. 重新编译(如有 .proto 变更先执行)
# bash scripts/compile-proto.sh
# 3. 重新编译所有二进制文件
cd $BASE/gateway && go build -ldflags="-s -w" -o /opt/topfans/gateway .
cd $BASE/services/userService && go build -ldflags="-s -w" -o /opt/topfans/user-service .
cd $BASE/services/galleryService && go build -ldflags="-s -w" -o /opt/topfans/gallery-service .
cd $BASE/services/socialService && go build -ldflags="-s -w" -o /opt/topfans/social-service .
cd $BASE/services/assetService && go build -ldflags="-s -w" -o /opt/topfans/asset-service .
cd $BASE/services/activityService && go build -ldflags="-s -w" -o /opt/topfans/activity-service .
# 4. 重启所有服务
sudo systemctl restart topfans-user topfans-gallery topfans-social \
topfans-asset topfans-activity topfans-gateway
# 5. 确认服务全部正常
sudo systemctl status topfans-*
```
---
## 故障排查
### 问题 1: 服务无法启动
```bash
# 查看详细错误日志
sudo journalctl -u topfans-gateway -xe
# 检查端口是否被占用
sudo ss -tlnp | grep 8080
# 手动执行二进制,直接查看输出
sudo -u topfans \
env $(cat /etc/topfans/common.env /etc/topfans/gateway.env | grep -v '^#') \
/opt/topfans/gateway
```
### 问题 2: 数据库连接失败
```bash
# 确认 PostgreSQL 运行中
sudo systemctl status postgresql
# 验证连接参数(与 common.env 一致)
psql -h localhost -U topfans_user -d top-fans
# 检查 common.env 中的数据库配置
sudo cat /etc/topfans/common.env | grep DB_
```
### 问题 3: Dubbo 服务连接失败
```bash
# 检查下游服务是否运行并监听端口
sudo ss -tlnp | grep -E '2000[0-4]'
# 检查服务日志
sudo journalctl -u topfans-user -n 50
# 确认服务私有 env 中的 URL 配置正确
sudo cat /etc/topfans/social.env
```
### 问题 4: 环境变量未生效
```bash
# 查看 systemd 实际注入的环境变量
sudo systemctl show topfans-user --property=Environment
# 手动验证 env 文件语法(不应含 export 前缀)
sudo cat /etc/topfans/common.env
```
### 问题 5: Proto 文件编译失败
```bash
# 检查工具是否安装
protoc --version
which protoc-gen-go
which protoc-gen-go-triple
# 手动编译单个 proto 文件测试
cd ~/projects/TopFans/backend
protoc --proto_path=proto \
--go_out=pkg/proto/user \
--go_opt=paths=source_relative \
user.proto
```
---
## 性能优化建议
### 1. 数据库优化
```bash
sudo vim /etc/postgresql/14/main/postgresql.conf
# 根据服务器内存调整(以下为 8 GB 内存示例)
shared_buffers = 2GB
effective_cache_size = 6GB
maintenance_work_mem = 512MB
work_mem = 32MB
max_connections = 200
sudo systemctl restart postgresql
```
### 2. 系统参数优化
```bash
sudo vim /etc/security/limits.conf
# 添加:
* soft nofile 65535
* hard nofile 65535
sudo vim /etc/sysctl.conf
# 添加:
net.core.somaxconn = 1024
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.ip_local_port_range = 10000 65000
sudo sysctl -p
```
### 3. 日志轮转
```bash
sudo vim /etc/logrotate.d/topfans
```
```
/var/log/topfans/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 0644 topfans topfans
}
```
---
## 监控与备份
### 服务健康检查脚本
```bash
vim ~/health-check.sh
```
```bash
#!/bin/bash
SERVICES=(topfans-user topfans-gallery topfans-social topfans-asset topfans-activity topfans-gateway)
LOG=/var/log/topfans-health.log
for svc in "${SERVICES[@]}"; do
if ! systemctl is-active --quiet "$svc"; then
echo "$(date '+%F %T'): $svc is down, restarting..." >> "$LOG"
systemctl restart "$svc"
fi
done
```
```bash
chmod +x ~/health-check.sh
# 每 5 分钟检查一次
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/topfans/health-check.sh") | crontab -
```
### 数据库备份脚本
```bash
vim ~/backup-db.sh
```
```bash
#!/bin/bash
BACKUP_DIR="/home/topfans/backups"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p "$BACKUP_DIR"
pg_dump -h localhost -U topfans_user -d top-fans > "$BACKUP_DIR/topfans_$DATE.sql"
gzip "$BACKUP_DIR/topfans_$DATE.sql"
# 保留最近 7 天
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +7 -delete
echo "$(date '+%F %T'): Backup done: topfans_$DATE.sql.gz" >> /var/log/topfans-backup.log
```
```bash
chmod +x ~/backup-db.sh
# 每天凌晨 2 点备份
(crontab -l 2>/dev/null; echo "0 2 * * * /home/topfans/backup-db.sh") | crontab -
```
---
## 多机部署说明
当业务量增长需要将服务拆分到多台服务器时,只需修改各服务器上对应服务私有 env 文件中的下游地址,将 `localhost` 替换为目标服务器的**内网 IP**,无需改动代码。
### 示例双机部署DB 服务器 + 应用服务器)
**DB 服务器**IP: `10.0.0.10`):仅运行 PostgreSQL。
**应用服务器**IP: `10.0.0.20`):运行所有后端服务,修改 `common.env` 中的 DB 地址:
```ini
# /etc/topfans/common.env应用服务器
DB_HOST=10.0.0.10 # 改为 DB 服务器内网 IP
```
### 示例:三机部署(拆分 Asset/Gallery 服务)
| 服务器 | 运行服务 |
|---|---|
| `10.0.0.20`应用1| userService, socialService, activityService, gateway |
| `10.0.0.21`应用2| galleryService, assetService |
| `10.0.0.10`DB| PostgreSQL |
在应用1服务器的 `social.env``activity.env` 中:
```ini
# /etc/topfans/social.env应用1服务器
ASSET_SERVICE_URL=tri://10.0.0.21:20003 # 指向应用2内网 IP
```
在应用1的 `gateway.env` 中:
```ini
# /etc/topfans/gateway.env应用1服务器
DUBBO_GALLERY_SERVICE_URL=tri://10.0.0.21:20001
DUBBO_ASSET_SERVICE_URL=tri://10.0.0.21:20003
```
> **后续扩展**: 如需引入服务注册与发现(如 Nacos各服务的 `configs/dubbo.yaml` 已预留占位配置,启用时取消注释并在 `main.go` 中调用 `config.Load()` 即可。
---
## 安全建议
1. **强密码**: `DB_PASSWORD`、`JWT_SECRET` 使用 32 位以上随机字符串
2. **最小权限**: 服务以 `topfans` 用户运行,不使用 root
3. **env 文件权限**: `chmod 640`,仅 `topfans` 用户可读
4. **防火墙**: 仅对外开放 8080Dubbo 端口20000-20004限内网访问
5. **HTTPS**: 生产环境通过 Nginx 反向代理对外暴露 443 端口
6. **定期更新**: 及时更新系统包和 Go 依赖
7. **备份验证**: 每月手动恢复一次备份,验证其可用性