gcx/docs/guides/09-编译部署指南.md

595 lines
19 KiB
Markdown
Raw 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.

# 09 — 编译部署指南
> 本文档涵盖 Genex 券金融平台全栈系统的编译、运行与生产部署流程。
---
## 目录
- [1. 前置条件](#1-前置条件)
- [2. 本地一键启动](#2-本地一键启动)
- [2.1 启动后端(基础设施 + 微服务)](#21-启动后端基础设施--微服务)
- [2.2 数据库迁移与种子数据](#22-数据库迁移与种子数据)
- [2.3 启动区块链网络](#23-启动区块链网络)
- [2.4 部署智能合约](#24-部署智能合约)
- [2.5 启动区块浏览器(可选)](#25-启动区块浏览器可选)
- [2.6 启动监控栈(可选)](#26-启动监控栈可选)
- [2.7 启动管理后台前端](#27-启动管理后台前端)
- [2.8 运行端到端测试](#28-运行端到端测试)
- [3. 单独编译各组件](#3-单独编译各组件)
- [3.1 NestJS 后端服务](#31-nestjs-后端服务)
- [3.2 Go 后端服务](#32-go-后端服务)
- [3.3 Genex 区块链节点](#33-genex-区块链节点)
- [3.4 智能合约Foundry](#34-智能合约foundry)
- [3.5 Flutter 移动端](#35-flutter-移动端)
- [3.6 管理后台 Next.js](#36-管理后台-nextjs)
- [3.7 小程序 (Taro)](#37-小程序-taro)
- [4. Docker 镜像构建](#4-docker-镜像构建)
- [4.1 NestJS 服务镜像](#41-nestjs-服务镜像)
- [4.2 Go 服务镜像](#42-go-服务镜像)
- [4.3 Genex Chain 镜像](#43-genex-chain-镜像)
- [4.4 Admin Web 镜像](#44-admin-web-镜像)
- [5. 生产部署](#5-生产部署)
- [5.1 Admin Web + Nginx + SSL](#51-admin-web--nginx--ssl)
- [5.2 安全加固要点](#52-安全加固要点)
- [5.3 环境变量配置](#53-环境变量配置)
- [6. 基础设施配置](#6-基础设施配置)
- [6.1 Kong API 网关路由表](#61-kong-api-网关路由表)
- [6.2 健康检查](#62-健康检查)
- [7. 端口总览](#7-端口总览)
- [8. CI/CD 管线](#8-cicd-管线)
---
## 1. 前置条件
| 工具 | 版本要求 | 用途 |
|------|----------|------|
| Docker + Docker Compose | 最新稳定版 | 容器编排,全栈运行 |
| Node.js | 20+ | NestJS 服务、Admin Web、小程序 |
| Go | 1.22+ | Trading / Translate / Chain-Indexer / Genex Chain |
| Flutter | 3.x | genex-mobile / admin-app |
| Foundry (forge) | 最新 nightly | 智能合约编译与测试 |
| PostgreSQL 客户端(可选) | 15+ | 手动执行迁移脚本 |
---
## 2. 本地一键启动
> 最简路径:在 `backend/` 和 `blockchain/` 目录分别执行 `docker compose up -d`,即可拉起完整后端 + 区块链环境。所有 API 通过 Kong 网关统一暴露在 `http://localhost:8080/api/v1/*`。
### 2.1 启动后端(基础设施 + 微服务)
```bash
cd backend/
cp .env.example .env # 首次需复制并按需修改
docker compose up -d
```
该命令启动以下全部服务:
**基础设施6 组件):**
| 服务 | 技术 | 端口 | 说明 |
|------|------|------|------|
| PostgreSQL | 15 | 5432 | WAL 复制已启用(供 Debezium CDC |
| Redis | 7 | 6379 | 缓存、分布式锁 |
| Kafka | 7.7.0 KRaft | 9092 / 29092 | 消息队列(无 Zookeeper |
| MinIO | latest | 9000 / 9001 | S3 兼容对象存储 |
| Kafka Connect | Debezium 2.5.4 | 8083 | CDC 变更数据捕获 |
| Kong | 3.5 | 8080 / 8001 | API 网关(声明式配置) |
**NestJS 微服务7 个):**
| 服务 | 端口 | 职责 |
|------|------|------|
| auth-service | 3010 | JWT 认证、RBAC 权限 |
| user-service | 3001 | 用户、KYC、钱包、消息 |
| issuer-service | 3002 | 发行方、券管理 |
| clearing-service | 3004 | 清算结算、支付 |
| compliance-service | 3005 | KYC/AML、Travel Rule |
| ai-service | 3006 | AI 防腐层(外部 Agent 集群) |
| notification-service | 3008 | 邮件、短信、推送 |
**Go 微服务3 个):**
| 服务 | 端口 | 职责 |
|------|------|------|
| trading-service | 3003 | 内存撮合引擎(价格-时间优先) |
| translate-service | 3007 | UX 翻译、地址映射、Gas 补贴 |
| chain-indexer | 3009 | Genex Chain 区块索引 |
**辅助服务2 个):**
| 服务 | 端口 | 职责 |
|------|------|------|
| telemetry-service | 3011 | 用户在线状态、DAU、Prometheus 指标 |
| admin-service | 3012 | App 版本管理、OTA 更新 |
### 2.2 数据库迁移与种子数据
```bash
cd backend/
./scripts/migrate.sh # 仅迁移
./scripts/migrate.sh --seed # 迁移 + 种子数据
```
共 31 个 SQL 迁移文件,按文件名顺序执行。默认连接:`postgresql://genex:genex_dev@localhost:5432/genex`。
### 2.3 启动区块链网络
```bash
cd blockchain/
docker compose up -d
```
启动 6 个节点的验证者网络:
| 节点 | 角色 | 区域标识 |
|------|------|----------|
| genex-node-1 | 创世验证者(主) | us-east-1 |
| genex-node-2 | 创世验证者 | us-west-1 |
| genex-node-3 | 创世验证者 | sg-1 |
| genex-inst-1 | 机构验证者 | — |
| genex-inst-2 | 机构验证者 | — |
| genex-regulatory | 监管只读节点 | — |
链参数Chain ID = `genex-1`(生产)/ `genex-localnet`开发EVM Chain ID = `8888`Denom = `agnx`18 位精度)。
### 2.4 部署智能合约
```bash
cd blockchain/
docker compose --profile deploy run contract-deployer
```
一次性任务,部署 9 个核心合约到链上。
### 2.5 启动区块浏览器(可选)
```bash
cd blockchain/
docker compose -f docker-compose.yml -f docker-compose.explorer.yml up -d
```
| 服务 | 端口 | 说明 |
|------|------|------|
| Blockscout | 4000 | EVM 区块浏览器 |
| Blockscout DB | — | PostgreSQL 16200 连接2GB shared_buffers |
| Blockscout Redis | 6380 | 512MB maxmemoryallkeys-lru |
| Smart Contract Verifier | 8050 | Solidity 编译器验证 |
访问:`http://localhost:4000`
### 2.6 启动监控栈(可选)
```bash
cd blockchain/chain-monitor/
docker compose -f docker-compose.monitor.yml up -d
```
| 服务 | 端口 | 说明 |
|------|------|------|
| Prometheus | 9090 | 指标采集90 天保留) |
| Grafana | 3030 | 可视化仪表板(密码:`genex_admin_2024` |
| AlertManager | 9093 | 告警管理 |
| Node Exporter | 9100 | 主机指标 |
### 2.7 启动管理后台前端
```bash
cd frontend/admin-web/
docker compose up -d
```
访问:`http://localhost:3000`
### 2.8 运行端到端测试
```bash
cd backend/
./scripts/run-e2e.sh
```
测试覆盖:认证流程 → 用户资料 → 钱包操作 → 券搜索 → 消息 → 交易撮合 → AI 对话 → 管理后台(仪表板、用户、发行方、财务、风控、合规)。
Base URL`http://localhost:8080`Kong 网关)。
---
## 3. 单独编译各组件
### 3.1 NestJS 后端服务
```bash
cd backend/services/<service-name>/
npm ci
npm run build # 编译到 dist/
npm run start:dev # 开发模式(热重载)
npm run start:prod # 生产模式
npm run test # 单元测试
npm run test:e2e # E2E 测试
```
适用于auth-service、user-service、issuer-service、clearing-service、compliance-service、ai-service、notification-service、telemetry-service、admin-service。
### 3.2 Go 后端服务
```bash
cd backend/services/<service-name>/
go build -o <service-name> .
# 生产构建(静态链接、去符号表)
CGO_ENABLED=0 go build -ldflags="-s -w" -o <service-name> .
```
适用于trading-service、translate-service、chain-indexer。
### 3.3 Genex 区块链节点
```bash
cd blockchain/genex-chain/
make build # 输出: build/genexd
make install # 安装到 $GOPATH/bin
make test # 运行测试(-race -count=1
make lint # golangci-lint 代码检查
make format # gofmt 格式化
# 本地单节点测试网
make init-local # 初始化6 步:构建→清理→初始化→创建账户→配置创世→启动)
make start # 启动节点
# Docker
make docker # 构建 Docker 镜像
make docker-run # 运行容器
make docker-stop # 停止容器
```
构建参数:`CGO_ENABLED=1`Cosmos SDK 加密库要求)。
### 3.4 智能合约Foundry
```bash
cd blockchain/genex-contracts/
forge build # 编译合约
forge build --sizes # 编译 + 显示合约大小(上限 24KB
forge test -vvv # 运行 102 个测试
forge test -vvv --gas-report # 运行测试 + Gas 报告
```
合约9 个核心合约Solidity 0.8.20。
### 3.5 Flutter 移动端
```bash
cd frontend/
# 消费端 App
./build.sh mobile debug # Debug APK
./build.sh mobile release # Release APK
./build.sh mobile release appbundle # Google Play AAB
./build.sh mobile clean # 清理
# 管理端 App
./build.sh admin-app debug
./build.sh admin-app release appbundle
# 全部构建
./build.sh all release
```
### 3.6 管理后台 Next.js
```bash
cd frontend/admin-web/
npm ci
npm run build # Next.js 15 生产构建
npm run dev # 开发模式
npm run start # 生产启动
npm run lint # 代码检查
```
### 3.7 小程序 (Taro)
```bash
cd frontend/miniapp/
npm ci
npm run dev:weapp # 微信小程序开发模式
npm run build:weapp # 微信小程序生产构建
npm run dev:h5 # H5 开发模式
npm run build:h5 # H5 生产构建
```
---
## 4. Docker 镜像构建
所有服务均采用**多阶段构建**以减小镜像体积。
### 4.1 NestJS 服务镜像
```dockerfile
# 构建阶段
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# 运行阶段
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json .
USER node
CMD ["dumb-init", "node", "dist/main"]
```
### 4.2 Go 服务镜像
```dockerfile
# 构建阶段
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o service .
# 运行阶段
FROM alpine:3.19
COPY --from=builder /app/service /usr/local/bin/
USER nobody:nobody
CMD ["service"]
```
### 4.3 Genex Chain 镜像
```dockerfile
FROM golang:1.23-alpine AS builder
# CGO_ENABLED=1Cosmos SDK 加密库需要)
# ldflags 注入: Name, AppName, Version, Commit, BuildTags
FROM alpine:3.19
USER genex:genex
EXPOSE 26656 26657 8545 8546 1317 9090 9091
HEALTHCHECK CMD curl -f http://localhost:26657/status || exit 1
```
### 4.4 Admin Web 镜像
```dockerfile
FROM node:20-alpine AS deps # npm ci
FROM node:20-alpine AS builder # npm run build
FROM node:20-alpine AS runner # node server.js
```
---
## 5. 生产部署
### 5.1 Admin Web + Nginx + SSL
```bash
cd frontend/admin-web/
# Docker 容器管理
./deploy.sh build # 构建镜像
./deploy.sh start # 构建并启动(默认)
./deploy.sh stop # 停止服务
./deploy.sh restart # 重启
./deploy.sh logs # 查看日志
./deploy.sh status # 服务状态
./deploy.sh clean # 移除容器和镜像
# Nginx + Let's Encrypt SSL
sudo ./deploy.sh nginx install <domain> <email> # 安装 Nginx + 申请证书
sudo ./deploy.sh nginx ssl <domain> <email> # 申请/续期证书
./deploy.sh nginx status # 检查 Nginx 状态
./deploy.sh nginx reload # 重载配置
```
默认域名:`admin.gogenex.cn`,健康检查:`http://localhost:3000/api/health`。
### 5.2 安全加固要点
| 措施 | 说明 |
|------|------|
| 端口绑定 | PG、Redis、Kafka Connect、Kong Admin、MinIO Console 仅绑定 `127.0.0.1` |
| 非 root 用户 | 容器内使用 `node` / `nobody` / `genex` 用户 |
| 优雅关闭 | NestJS 服务使用 `dumb-init` |
| WAL 管理 | `max_slot_wal_keep_size=10GB` 防止复制槽磁盘溢出 |
| 网关隔离 | 仅 Kong Proxy 端口(8080) 对外暴露 |
### 5.3 环境变量配置
参考 `backend/.env.example`,以下为核心配置项:
```bash
# ---- 数据库 ----
DB_HOST=postgres
DB_PORT=5432
DB_USERNAME=genex
DB_PASSWORD=genex_dev_password # 生产环境必须修改
DB_NAME=genex
# ---- Redis ----
REDIS_HOST=redis
REDIS_PORT=6379
# ---- Kafka ----
KAFKA_BROKERS=kafka:9092
# ---- JWT生产环境必须修改 ----
JWT_ACCESS_SECRET=dev-access-secret-change-in-production
JWT_ACCESS_EXPIRY=15m
JWT_REFRESH_SECRET=dev-refresh-secret-change-in-production
JWT_REFRESH_EXPIRY=7d
# ---- Kong ----
KONG_ADMIN_URL=http://kong:8001
KONG_PROXY_PORT=8080
# ---- MinIO ----
MINIO_ENDPOINT=minio
MINIO_PORT=9000
MINIO_ACCESS_KEY=genex-admin
MINIO_SECRET_KEY=genex-minio-secret # 生产环境必须修改
# ---- AI 服务 ----
AI_SERVICE_URL=http://ai-agent-cluster:3006
AI_SERVICE_API_KEY=your-ai-service-api-key
AI_SERVICE_TIMEOUT=30000
# ---- 区块链 ----
CHAIN_RPC_URL=http://localhost:26657
# ---- 外部服务MVP 阶段 Mock ----
SENDGRID_API_KEY=mock-key
TWILIO_SID=mock-sid
TWILIO_AUTH_TOKEN=mock-token
CHAINALYSIS_API_KEY=mock-key
```
---
## 6. 基础设施配置
### 6.1 Kong API 网关路由表
配置文件:`backend/kong/kong.yml`YAML 3.0 声明式)
| 服务 | 上游端口 | 路由前缀 |
|------|----------|----------|
| auth-service | 3010 | `/api/v1/auth` |
| user-service | 3001 | `/api/v1/users`、`/api/v1/wallet`、`/api/v1/messages`、`/api/v1/admin/users` |
| issuer-service | 3002 | `/api/v1/coupons`、`/api/v1/issuers`、`/api/v1/admin/issuers`、`/api/v1/admin/coupons` |
| trading-service | 3003 | `/api/v1/trades`、`/api/v1/mm`、`/api/v1/admin/trading` |
| clearing-service | 3004 | `/api/v1/payments`、`/api/v1/admin/finance` |
| compliance-service | 3005 | `/api/v1/compliance`、`/api/v1/disputes` |
| ai-service | 3006 | `/api/v1/ai` |
| translate-service | 3007 | `/api/v1/translate` |
| notification-service | 3008 | `/api/v1/notifications`、`/api/v1/admin/notifications` |
| chain-indexer | 3009 | `/api/v1/blockchain` |
| telemetry-service | 3011 | `/api/v1/telemetry`、`/api/v1/admin/telemetry` |
| admin-service | 3012 | `/api/v1/app/version`、`/api/v1/admin/versions` |
所有路由配置 `strip_path: false`
### 6.2 健康检查
| 服务 | 检查方式 | 间隔 |
|------|----------|------|
| PostgreSQL | `pg_isready` | 5s |
| Redis | `redis-cli ping` | 5s |
| Kafka | `kafka-broker-api-versions` | 10s |
| MinIO | `mc ready local` | 10s |
| Kong | `kong health` | 10s |
| Genex Chain | `curl /status` | 30s |
| Blockscout | `GET /api/v2/stats` | 30s启动宽限 120s |
---
## 7. 端口总览
| 服务 | 端口 | 对外绑定 | 说明 |
|------|------|----------|------|
| **Kong Proxy** | 8080 | `0.0.0.0` | API 统一入口 |
| Kong Admin | 8001 | `127.0.0.1` | 网关管理 |
| PostgreSQL | 5432 | `127.0.0.1` | 数据库 |
| Redis | 6379 | `127.0.0.1` | 缓存 |
| Kafka | 9092 | `0.0.0.0` | 消息队列 |
| Kafka External | 29092 | `127.0.0.1` | 外部客户端 |
| MinIO S3 | 9000 | `0.0.0.0` | 对象存储 |
| MinIO Console | 9001 | `127.0.0.1` | MinIO 管理界面 |
| Kafka Connect | 8083 | `127.0.0.1` | CDC 连接器 |
| **Genex Chain RPC** | 26657 | `0.0.0.0` | CometBFT RPC |
| Genex Chain P2P | 26656 | `0.0.0.0` | 节点发现 |
| **Genex EVM RPC** | 8545 | `0.0.0.0` | EVM JSON-RPC |
| Genex EVM WS | 8546 | `0.0.0.0` | EVM WebSocket |
| Cosmos REST | 1317 | `0.0.0.0` | Cosmos LCD |
| Cosmos gRPC | 9090 | `0.0.0.0` | Cosmos gRPC |
| **Blockscout** | 4000 | `0.0.0.0` | 区块浏览器 |
| Contract Verifier | 8050 | — | 合约验证 |
| **Prometheus** | 9090 | `0.0.0.0` | 指标采集 |
| **Grafana** | 3030 | `0.0.0.0` | 监控仪表板 |
| AlertManager | 9093 | `0.0.0.0` | 告警 |
| Node Exporter | 9100 | `0.0.0.0` | 主机指标 |
| **Admin Web** | 3000 | `0.0.0.0` | 管理后台前端 |
| Enterprise API | 3020 | `0.0.0.0` | 企业级 API |
| Wallet Service | 3021 | `0.0.0.0` | 钱包服务 |
| Gas Relayer | 3022 | `0.0.0.0` | Gas 代付 |
| Faucet | 3023 | `0.0.0.0` | 测试网水龙头 |
| Bridge Monitor | 3024 | `0.0.0.0` | 跨链监控 |
---
## 8. CI/CD 管线
### 8.1 智能合约安全管线
文件:`blockchain/.github/workflows/contract-security.yml`
触发条件:`blockchain/genex-contracts/**` 文件变更
```
┌─────────────────┐ ┌─────────────────────┐ ┌────────────────────────┐
│ Foundry Tests │────▶│ Slither 静态分析 │────▶│ Mythril 符号执行 │
│ forge test -vvv │ │ 中等以上 severity │ │ timeout=300s depth=24 │
│ + Gas Report │ │ 输出 SARIF │ │ 输出 JSON │
│ + Size Check │ │ │ │ │
└─────────────────┘ └─────────────────────┘ └────────────────────────┘
▼ (main branch only)
┌────────────────────────┐
│ Blockscout 合约验证 │
│ forge verify │
└────────────────────────┘
```
### 8.2 区块链 CI 管线
文件:`blockchain/.github/workflows/chain-ci.yml`
触发条件:`blockchain/` 下 Go 相关文件变更
```
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ genexd 构建 │ │ Go SDK 测试 │ │ Bridge Monitor │
│ make build │ │ go test ./... │ │ go test ./... │
│ go test -race │ │ │ │ │
│ golangci-lint │ │ │ │ │
└──────────────────┘ └──────────────────┘ └──────────────────┘
┌─────────────────────────────────────────┐ ┌──────────────────┐
│ Ecosystem Services Build (matrix) │ │ Dart SDK 测试 │
│ enterprise-api / gas-relayer / faucet │ │ dart analyze │
│ npm ci → npm run build → npm run lint │ │ dart test │
└─────────────────────────────────────────┘ └──────────────────┘
```
---
## 附录:快速参考
```bash
# === 全栈本地启动(最简路径) ===
cd backend && docker compose up -d # 后端全部
cd blockchain && docker compose up -d # 区块链全部
cd frontend/admin-web && docker compose up -d # 管理后台
# === 验证 ===
curl http://localhost:8080/api/v1/auth/health # Kong → Auth 健康
curl http://localhost:26657/status # 区块链节点状态
curl http://localhost:3000 # 管理后台页面
# === 停止 ===
cd backend && docker compose down
cd blockchain && docker compose down
cd frontend/admin-web && docker compose down
```