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

24 KiB
Raw Blame History

09 — 编译部署指南

本文档涵盖 Genex 券金融平台全栈系统的编译、运行与生产部署流程。


目录


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 启动后端(基础设施 + 微服务)

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 数据库迁移与种子数据

cd backend/
./scripts/migrate.sh          # 仅迁移
./scripts/migrate.sh --seed   # 迁移 + 种子数据

共 31 个 SQL 迁移文件,按文件名顺序执行。默认连接:postgresql://genex:genex_dev@localhost:5432/genex

2.3 启动区块链网络

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 = 8888Denom = agnx18 位精度)。

2.4 部署智能合约

cd blockchain/
docker compose --profile deploy run contract-deployer

一次性任务,部署 9 个核心合约到链上。

2.5 启动区块浏览器(可选)

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 启动监控栈(可选)

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 启动管理后台前端

cd frontend/admin-web/
docker compose up -d

访问:http://localhost:3000

2.8 运行端到端测试

cd backend/
./scripts/run-e2e.sh

测试覆盖:认证流程 → 用户资料 → 钱包操作 → 券搜索 → 消息 → 交易撮合 → AI 对话 → 管理后台(仪表板、用户、发行方、财务、风控、合规)。

Base URLhttp://localhost:8080Kong 网关)。


3. 单独编译各组件

3.1 NestJS 后端服务

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 后端服务

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 区块链节点

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=1Cosmos SDK 加密库要求)。

3.4 智能合约Foundry

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 移动端

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

cd frontend/admin-web/
npm ci
npm run build       # Next.js 15 生产构建
npm run dev         # 开发模式
npm run start       # 生产启动
npm run lint        # 代码检查

3.7 小程序 (Taro)

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 服务镜像

# 构建阶段
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 服务镜像

# 构建阶段
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 镜像

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 镜像

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

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,以下为核心配置项:

# ---- 数据库 ----
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.ymlYAML 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        │
└─────────────────────────────────────────┘  └──────────────────┘

9. deploy.sh 部署管理脚本

每个模块都配备了 deploy.sh 脚本,提供统一的服务管理接口(启动、停止、重启、编译、健康检查等),所有服务在总 docker-compose.yml + .env 下有序工作。

9.1 后端主控脚本 — backend/deploy.sh

# 首次初始化(自动生成安全密钥 + .env
./deploy.sh install

# 全局操作
./deploy.sh up                # 启动全部 (基础设施 + 12个微服务)
./deploy.sh down              # 停止全部
./deploy.sh restart           # 重启全部
./deploy.sh build             # 增量编译全部镜像
./deploy.sh build-no-cache    # 全新编译 (无缓存)
./deploy.sh status            # 状态 + 健康检查
./deploy.sh health            # 仅健康检查
./deploy.sh logs [svc]        # 日志 (可指定服务)
./deploy.sh migrate           # 数据库迁移

# 基础设施单独控制
./deploy.sh infra-up          # 仅启动 PG/Redis/Kafka/MinIO/Kong
./deploy.sh infra-down
./deploy.sh infra-restart
./deploy.sh infra-status
./deploy.sh infra-logs
./deploy.sh infra-clean       # 清理 (删除数据!)
./deploy.sh infra-reset       # 重置 (clean + 重启)

# 单服务操作
./deploy.sh start-svc auth-service
./deploy.sh stop-svc auth-service
./deploy.sh restart-svc auth-service
./deploy.sh rebuild-svc auth-service              # 增量编译并重启
./deploy.sh rebuild-svc auth-service --no-cache   # 全新编译并重启
./deploy.sh logs-svc auth-service

9.2 各服务独立脚本 — backend/services/<name>/deploy.sh

每个微服务目录下都有独立的 deploy.sh,支持以下命令:

cd backend/services/auth-service/
./deploy.sh build             # 增量编译
./deploy.sh build-no-cache    # 全新编译 (无缓存)
./deploy.sh start             # 启动
./deploy.sh stop              # 停止
./deploy.sh restart           # 重启
./deploy.sh rebuild           # 增量编译并重启
./deploy.sh rebuild-no-cache  # 全新编译并重启
./deploy.sh logs              # 实时日志
./deploy.sh logs-tail         # 最近 100 行
./deploy.sh status            # 运行状态
./deploy.sh health            # 健康检查
./deploy.sh shell             # 进入容器
./deploy.sh test              # 运行测试 (NestJS: npm test / Go: go test)
服务 路径 端口 类型
auth-service backend/services/auth-service/deploy.sh 3010 NestJS
user-service backend/services/user-service/deploy.sh 3001 NestJS
issuer-service backend/services/issuer-service/deploy.sh 3002 NestJS
trading-service backend/services/trading-service/deploy.sh 3003 Go
clearing-service backend/services/clearing-service/deploy.sh 3004 NestJS
compliance-service backend/services/compliance-service/deploy.sh 3005 NestJS
ai-service backend/services/ai-service/deploy.sh 3006 NestJS
translate-service backend/services/translate-service/deploy.sh 3007 Go
notification-service backend/services/notification-service/deploy.sh 3008 NestJS
chain-indexer backend/services/chain-indexer/deploy.sh 3009 Go
telemetry-service backend/services/telemetry-service/deploy.sh 3011 NestJS
admin-service backend/services/admin-service/deploy.sh 3012 NestJS

9.3 区块链脚本 — blockchain/deploy.sh

# 节点管理
./deploy.sh up                # 启动全部节点 (3创世+2机构+1监管)
./deploy.sh down              # 停止
./deploy.sh restart           # 重启
./deploy.sh dev               # 单节点开发模式 (仅 node-1)
./deploy.sh build             # 增量编译
./deploy.sh build-no-cache    # 全新编译
./deploy.sh status            # 状态 + 健康
./deploy.sh health            # 健康检查

# 生态服务
./deploy.sh eco-up            # Enterprise API / Gas Relayer / Faucet / Bridge / Archive
./deploy.sh eco-down
./deploy.sh eco-status
./deploy.sh eco-build
./deploy.sh eco-build-no-cache

# 智能合约
./deploy.sh deploy-contracts  # 部署合约
./deploy.sh test-contracts    # Foundry 测试

# 区块浏览器
./deploy.sh explorer-up       # 启动 Blockscout (:4000)
./deploy.sh explorer-down

# 链监控
./deploy.sh monitor-up        # Prometheus(:9090) + Grafana(:3030)
./deploy.sh monitor-down

# 单服务
./deploy.sh rebuild-svc genex-node-1 --no-cache

9.4 编译策略说明

命令 策略 场景
build 增量编译 日常开发,利用 Docker 层缓存,速度快
build-no-cache 全新编译 依赖变更、Dockerfile 修改后,跳过所有缓存
rebuild 增量编译 + 自动重启 修改代码后快速更新
rebuild-no-cache 全新编译 + 自动重启 确保干净环境

附录:快速参考

# === 全栈本地启动deploy.sh 方式,推荐) ===
cd backend && ./deploy.sh install && ./deploy.sh build && ./deploy.sh up
cd blockchain && ./deploy.sh build && ./deploy.sh up
cd frontend/admin-web && docker compose up -d

# === 验证 ===
cd backend && ./deploy.sh health
cd blockchain && ./deploy.sh health
curl http://localhost:3000                      # 管理后台页面

# === 单服务热更新 ===
cd backend && ./deploy.sh rebuild-svc auth-service           # 增量
cd backend && ./deploy.sh rebuild-svc trading-service --no-cache  # 全新

# === 停止 ===
cd backend && ./deploy.sh down
cd blockchain && ./deploy.sh down
cd frontend/admin-web && docker compose down