Files
telegram-management-system/DEPLOYMENT.md
你的用户名 237c7802e5
Some checks failed
Deploy / deploy (push) Has been cancelled
Initial commit: Telegram Management System
Full-stack web application for Telegram management
- Frontend: Vue 3 + Vben Admin
- Backend: NestJS
- Features: User management, group broadcast, statistics

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 15:37:50 +08:00

23 KiB
Raw Blame History

Telegram Management System - 部署指南

本文档详细介绍了Telegram Management System的部署流程、配置选项和运维最佳实践。

目录

系统架构

技术栈

  • 后端: Node.js + Hapi.js + Sequelize ORM
  • 前端: Vue.js + iView UI
  • 数据库: MySQL 8.0+
  • 缓存: Redis 6.0+
  • 消息队列: Redis (内置队列系统)
  • 进程管理: PM2
  • Web服务器: Nginx (可选)

系统组件

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Frontend      │    │   Backend API   │    │   Database      │
│   (Vue.js)      │◄──►│   (Node.js)     │◄──►│   (MySQL)       │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                              │
                              ▼
                       ┌─────────────────┐
                       │   Redis Cache   │
                       │   & Queue       │
                       └─────────────────┘

环境要求

硬件要求

最低配置:

  • CPU: 2核心 2.0GHz
  • 内存: 4GB RAM
  • 存储: 50GB SSD
  • 网络: 100Mbps

推荐配置:

  • CPU: 4核心 2.5GHz+
  • 内存: 8GB+ RAM
  • 存储: 100GB+ SSD
  • 网络: 1Gbps

生产环境:

  • CPU: 8核心 3.0GHz+
  • 内存: 16GB+ RAM
  • 存储: 200GB+ SSD (RAID1)
  • 网络: 1Gbps+ (双线冗余)

软件依赖

必需软件:

  • Node.js 18.x LTS
  • MySQL 8.0+
  • Redis 6.0+
  • Git 2.x

可选软件:

  • Nginx 1.20+
  • PM2 5.x
  • Docker 20.x+
  • Docker Compose 2.x

安装部署

方式一:传统部署

1. 环境准备

# 更新系统
sudo apt update && sudo apt upgrade -y

# 安装Node.js 18.x LTS
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# 安装MySQL 8.0
sudo apt install mysql-server-8.0
sudo mysql_secure_installation

# 安装Redis
sudo apt install redis-server

# 安装PM2
sudo npm install -g pm2

# 安装Nginx可选
sudo apt install nginx

2. 数据库配置

-- 创建数据库
CREATE DATABASE telegram_management CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 创建用户
CREATE USER 'tg_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON telegram_management.* TO 'tg_user'@'localhost';
FLUSH PRIVILEGES;

3. 应用部署

# 克隆代码
git clone https://github.com/your-org/telegram-management-system.git
cd telegram-management-system

# 安装后端依赖
cd backend
npm install --production

# 安装前端依赖并构建Vben Admin
corepack enable
cd ../frontend-vben
pnpm install
pnpm run build:antd

# 构建产物位于 apps/web-antd/dist可部署到静态资源服务器

# 返回根目录
cd ..

4. 配置文件

创建 backend/config/production.json:

{
  "database": {
    "host": "localhost",
    "port": 3306,
    "database": "telegram_management",
    "username": "tg_user",
    "password": "your_secure_password",
    "logging": false,
    "pool": {
      "max": 20,
      "min": 5,
      "acquire": 30000,
      "idle": 10000
    }
  },
  "redis": {
    "host": "localhost",
    "port": 6379,
    "password": "",
    "db": 0
  },
  "server": {
    "host": "0.0.0.0",
    "port": 3000
  },
  "telegram": {
    "apiId": "your_api_id",
    "apiHash": "your_api_hash",
    "sessionPath": "./sessions"
  },
  "security": {
    "jwtSecret": "your_jwt_secret_key",
    "saltRounds": 12
  }
}

5. 启动服务

# 数据库迁移
cd backend
npm run migrate

# 启动后端服务
pm2 start ecosystem.config.js --env production

# 配置Nginx可选
sudo cp nginx.conf /etc/nginx/sites-available/telegram-management
sudo ln -s /etc/nginx/sites-available/telegram-management /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

方式二Docker部署

1. Docker Compose配置

创建 docker-compose.yml:

version: '3.8'

services:
  mysql:
    image: mysql:8.0
    container_name: tg_mysql
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: telegram_management
      MYSQL_USER: tg_user
      MYSQL_PASSWORD: user_password
    volumes:
      - mysql_data:/var/lib/mysql
      - ./mysql/init.sql:/docker-entrypoint-initdb.d/init.sql
    ports:
      - "3306:3306"
    command: --default-authentication-plugin=mysql_native_password
    restart: unless-stopped

  redis:
    image: redis:6.2-alpine
    container_name: tg_redis
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data
    ports:
      - "6379:6379"
    restart: unless-stopped

  backend:
    build: 
      context: ./backend
      dockerfile: Dockerfile
    container_name: tg_backend
    environment:
      NODE_ENV: production
      DB_HOST: mysql
      DB_PORT: 3306
      DB_NAME: telegram_management
      DB_USER: tg_user
      DB_PASS: user_password
      REDIS_HOST: redis
      REDIS_PORT: 6379
    ports:
      - "3000:3000"
    depends_on:
      - mysql
      - redis
    volumes:
      - ./backend/sessions:/app/sessions
      - ./backend/logs:/app/logs
    restart: unless-stopped

  frontend:
    build:
      context: ./frontend-vben
      dockerfile: Dockerfile
    container_name: tg_frontend
    environment:
      VITE_APP_NAMESPACE: production
    ports:
      - "80:80"
    depends_on:
      - backend
    restart: unless-stopped

volumes:
  mysql_data:
  redis_data:

2. Dockerfile配置

后端Dockerfile (backend/Dockerfile):

FROM node:18-alpine

WORKDIR /app

# 复制package文件
COPY package*.json ./

# 安装依赖
RUN npm ci --only=production && npm cache clean --force

# 复制源码
COPY . .

# 创建必要目录
RUN mkdir -p sessions logs

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1

# 暴露端口
EXPOSE 3000

# 启动命令
CMD ["npm", "start"]

前端Dockerfile (frontend-vben/apps/web-antd/Dockerfile):

# 构建阶段
FROM node:20-alpine AS builder

WORKDIR /app
RUN apk add --no-cache bash git python3 make g++ \
    && corepack enable \
    && corepack prepare pnpm@8.15.8 --activate

COPY pnpm-workspace.yaml package.json ./
COPY apps ./apps
COPY packages ./packages
COPY internal ./internal
COPY scripts ./scripts

# 安装依赖并构建 Admin 前端(无 lock 时自动解析最新依赖)
RUN pnpm install --no-frozen-lockfile
RUN pnpm add -D less sass --workspace-root
RUN pnpm --filter @vben/web-antd... build

# 生产阶段
FROM nginx:alpine

# 覆盖默认 Nginx 配置,支持单页应用路由
COPY apps/web-antd/nginx.conf /etc/nginx/conf.d/default.conf

# 拷贝构建产物
COPY --from=builder /app/apps/web-antd/dist /usr/share/nginx/html

# 暴露端口
EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

3. 启动Docker服务

# 构建并启动所有服务
docker-compose up -d

# 查看服务状态
docker-compose ps

# 查看日志
docker-compose logs -f backend

方式三GitHub Actions + Docker 自动部署

仓库内新增的 .github/workflows/deploy.yml 工作流支持在推送到 main 分支时自动将应用部署到远程服务器(同时支持 workflow_dispatch 手动触发)。整体流程为:打包代码 → 通过 SCP 传输 → 在目标服务器上解压并执行 docker compose up -d --build

1. 前置条件

  • 目标服务器已安装 Docker Engine (20+) 与 Docker Compose 插件(或 legacy docker-compose)。
  • 服务器 67.209.181.104:22 对外开放,并允许使用 root 账号远程登录。
  • 首次部署前建议在服务器上创建工作目录 mkdir -p /opt/telegram-management-system

2. 配置 GitHub Secrets

在仓库 Settings → Secrets and variables → Actions 中新增以下机密变量:

Secret Key 建议取值 说明
DEPLOY_HOST 67.209.181.104 目标服务器 IP
DEPLOY_USER root 登录用户名
DEPLOY_PASSWORD w8BzXrLbeQlk 登录密码(建议后续改为密钥登录)
DEPLOY_PORT 22(可选) SSH 端口,缺省为 22

安全建议:生产环境中请改用 SSH 私钥或只读部署账号,并将密码及时更换为强口令。

3. 工作流执行说明

  • 推送到 main 分支或在 Actions 中手动触发 Deploy 工作流即会发布最新版本。
  • 工作流会排除 node_moduleslogs 等目录,仅携带源码与 Docker 配置;前端镜像会在服务器端使用 pnpm 构建。
  • 在服务器 /tmp/telegram-management-system 下会暂存 release.tar.gz 与部署脚本 deploy/remote-deploy.sh,随后被执行以更新 /opt/telegram-management-system 并重启容器;脚本会自动停止宿主机 Nginx 并等待旧容器完全销毁后再启动新版本。
  • Docker 挂载的数据卷MySQL、Redis 等)不会被删除,执行的是无停机的滚动式重建。

4. 故障排查

  • 若部署失败,可在 GitHub Actions 控制台查看日志,确认网络连通性及凭证是否正确。
  • 服务器端可通过 docker compose logs -f 查看服务输出,或检查 /opt/telegram-management-system 中的日志文件。
  • 如需回滚,可回退 Git 提交或重新推送指定 commit 触发部署。

配置说明

环境变量

# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_NAME=telegram_management
DB_USER=tg_user
DB_PASS=your_password

# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=

# 服务器配置
SERVER_HOST=0.0.0.0
SERVER_PORT=3000
NODE_ENV=production

# Telegram配置
TG_API_ID=your_api_id
TG_API_HASH=your_api_hash
TG_SESSION_PATH=./sessions

# 安全配置
JWT_SECRET=your_jwt_secret
SALT_ROUNDS=12

# 日志配置
LOG_LEVEL=info
LOG_FILE_PATH=./logs
LOG_MAX_SIZE=100m
LOG_MAX_FILES=10

PM2配置

创建 ecosystem.config.js:

module.exports = {
  apps: [{
    name: 'telegram-management-backend',
    script: './src/app.js',
    cwd: './backend',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'development',
      PORT: 3000
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: './logs/pm2-error.log',
    out_file: './logs/pm2-out.log',
    log_file: './logs/pm2-combined.log',
    time: true,
    max_memory_restart: '1G',
    node_args: '--max-old-space-size=4096',
    watch: false,
    ignore_watch: ['node_modules', 'logs', 'sessions'],
    restart_delay: 4000,
    max_restarts: 10,
    min_uptime: '10s'
  }]
};

Nginx配置

创建 nginx.conf:

upstream backend {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name your-domain.com;
    
    # 重定向到HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;

    # SSL配置
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/private.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    ssl_prefer_server_ciphers off;

    # 前端静态文件
    location / {
        root /var/www/telegram-management/frontend/dist;
        try_files $uri $uri/ /index.html;
        
        # 缓存配置
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # API代理
    location /api/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        
        # 超时配置
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }

    # WebSocket代理
    location /ws/ {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 安全头
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
}

运维管理

服务管理

# PM2服务管理
pm2 start ecosystem.config.js --env production    # 启动
pm2 restart telegram-management-backend           # 重启
pm2 stop telegram-management-backend              # 停止
pm2 delete telegram-management-backend            # 删除
pm2 reload telegram-management-backend            # 零停机重载

# 查看状态和日志
pm2 status                                         # 查看状态
pm2 logs telegram-management-backend              # 查看日志
pm2 monit                                         # 监控界面

# 服务开机自启
pm2 startup
pm2 save

数据库管理

# 备份数据库
mysqldump -u tg_user -p telegram_management > backup_$(date +%Y%m%d_%H%M%S).sql

# 恢复数据库
mysql -u tg_user -p telegram_management < backup_file.sql

# 数据库优化
mysql -u root -p -e "OPTIMIZE TABLE telegram_management.*;"

# 查看数据库状态
mysql -u root -p -e "SHOW ENGINE INNODB STATUS\G"

Redis管理

# 连接Redis
redis-cli

# 查看Redis信息
redis-cli info

# 备份Redis数据
redis-cli --rdb /backup/redis_backup_$(date +%Y%m%d_%H%M%S).rdb

# 清理Redis缓存
redis-cli FLUSHDB

日志管理

# 查看应用日志
tail -f backend/logs/app.log

# 查看错误日志
tail -f backend/logs/error.log

# 日志轮转配置 (/etc/logrotate.d/telegram-management)
/var/www/telegram-management/backend/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    copytruncate
}

监控告警

系统监控

安装监控工具:

# 安装Node Exporter
wget https://github.com/prometheus/node_exporter/releases/download/v1.6.1/node_exporter-1.6.1.linux-amd64.tar.gz
tar xvfz node_exporter-1.6.1.linux-amd64.tar.gz
sudo mv node_exporter-1.6.1.linux-amd64/node_exporter /usr/local/bin/

健康检查端点:

系统提供以下健康检查端点:

  • GET /health - 基础健康检查
  • GET /health/detailed - 详细健康状态
  • GET /metrics - Prometheus格式指标

关键指标监控

系统指标:

  • CPU使用率 (< 80%)
  • 内存使用率 (< 85%)
  • 磁盘使用率 (< 90%)
  • 网络连接数

应用指标:

  • HTTP响应时间 (< 200ms)
  • 错误率 (< 1%)
  • 数据库连接池使用率 (< 80%)
  • Redis内存使用率 (< 75%)

业务指标:

  • 活跃账号数量
  • 任务成功率 (> 95%)
  • 风控触发频率
  • 消息发送量

告警配置

创建告警规则文件 alert-rules.yml:

groups:
- name: telegram-management-alerts
  rules:
  - alert: HighErrorRate
    expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.01
    for: 2m
    labels:
      severity: critical
    annotations:
      summary: High error rate detected
      description: "Error rate is {{ $value }} requests/second"

  - alert: HighMemoryUsage
    expr: node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes < 0.15
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: High memory usage
      description: "Memory usage is above 85%"

  - alert: DatabaseConnectionPoolHigh
    expr: mysql_global_status_threads_connected / mysql_global_variables_max_connections > 0.8
    for: 3m
    labels:
      severity: warning
    annotations:
      summary: Database connection pool high
      description: "Database connection pool usage is {{ $value }}%"

故障排查

常见问题

1. 服务无法启动

# 检查端口占用
netstat -tlnp | grep :3000

# 检查配置文件
node -c backend/src/app.js

# 查看详细错误
pm2 logs telegram-management-backend --lines 100

2. 数据库连接失败

# 测试数据库连接
mysql -h localhost -u tg_user -p telegram_management

# 检查数据库状态
sudo systemctl status mysql

# 查看数据库错误日志
sudo tail -f /var/log/mysql/error.log

3. Redis连接问题

# 测试Redis连接
redis-cli ping

# 检查Redis状态
sudo systemctl status redis

# 查看Redis日志
sudo tail -f /var/log/redis/redis-server.log

4. 内存不足

# 查看内存使用
free -h
top -o %MEM

# 重启服务释放内存
pm2 restart telegram-management-backend

# 调整PM2内存限制
pm2 start ecosystem.config.js --max-memory-restart 512M

调试模式

启用调试模式:

# 设置调试环境变量
export DEBUG=telegram-management:*
export NODE_ENV=development

# 启动调试模式
node --inspect backend/src/app.js

# 使用PM2调试
pm2 start ecosystem.config.js --node-args="--inspect"

性能分析

# 生成性能报告
node --prof backend/src/app.js

# 分析性能数据
node --prof-process isolate-0x*.log > performance-report.txt

# 内存快照
kill -USR2 $(pgrep -f "telegram-management-backend")

性能优化

数据库优化

MySQL配置优化 (/etc/mysql/mysql.conf.d/mysqld.cnf):

[mysqld]
# 内存配置
innodb_buffer_pool_size = 4G
innodb_log_file_size = 256M
innodb_log_buffer_size = 64M

# 连接配置
max_connections = 500
thread_cache_size = 50

# 查询缓存
query_cache_type = 1
query_cache_size = 256M

# 慢查询日志
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 2

索引优化:

-- 分析慢查询
EXPLAIN SELECT * FROM group_tasks WHERE status = 'running';

-- 添加必要索引
CREATE INDEX idx_group_tasks_status ON group_tasks(status);
CREATE INDEX idx_account_pool_health ON tg_account_pool(healthScore, status);
CREATE INDEX idx_risk_logs_created ON risk_logs(createdAt);

-- 定期分析表
ANALYZE TABLE group_tasks, tg_account_pool, risk_logs;

Redis优化

Redis配置优化 (/etc/redis/redis.conf):

# 内存配置
maxmemory 2gb
maxmemory-policy allkeys-lru

# 持久化配置
save 900 1
save 300 10
save 60 10000

# 网络配置
tcp-keepalive 300
timeout 0

# 安全配置
requirepass your_redis_password

应用优化

Node.js优化:

// 启用集群模式
if (cluster.isMaster) {
    const numCPUs = require('os').cpus().length;
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
} else {
    require('./app');
}

// 内存优化
process.on('warning', (warning) => {
    console.warn(warning.name);
    console.warn(warning.message);
    console.warn(warning.stack);
});

// 优化垃圾回收
node --max-old-space-size=4096 --optimize-for-size app.js

缓存策略:

// Redis缓存实现
const cache = {
    async get(key) {
        const value = await redis.get(key);
        return value ? JSON.parse(value) : null;
    },
    
    async set(key, value, ttl = 3600) {
        await redis.setex(key, ttl, JSON.stringify(value));
    },
    
    async del(key) {
        await redis.del(key);
    }
};

// 数据库连接池优化
const sequelize = new Sequelize(config.database, {
    pool: {
        max: 50,
        min: 10,
        acquire: 30000,
        idle: 10000
    }
});

安全加固

系统安全

防火墙配置:

# UFW防火墙
sudo ufw enable
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow from trusted_ip to any port 3306  # MySQL
sudo ufw allow from trusted_ip to any port 6379  # Redis

SSL/TLS配置:

# 使用Let's Encrypt证书
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

# 自动续期
sudo crontab -e
# 添加0 12 * * * /usr/bin/certbot renew --quiet

应用安全

环境变量保护:

# 创建.env文件并设置权限
touch .env
chmod 600 .env

# 敏感信息环境变量
echo "DB_PASSWORD=your_secure_password" >> .env
echo "JWT_SECRET=your_jwt_secret" >> .env
echo "TG_API_HASH=your_api_hash" >> .env

输入验证和SQL注入防护:

// 使用参数化查询
const users = await User.findAll({
    where: {
        email: req.params.email  // Sequelize自动转义
    }
});

// 输入验证
const Joi = require('joi');
const schema = Joi.object({
    email: Joi.string().email().required(),
    password: Joi.string().min(8).required()
});

访问控制:

// JWT认证中间件
const jwt = require('jsonwebtoken');

const authenticateToken = (req, res, next) => {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    
    if (!token) {
        return res.sendStatus(401);
    }
    
    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user;
        next();
    });
};

数据安全

数据加密:

const crypto = require('crypto');

// 敏感数据加密
const encrypt = (text, key) => {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipher('aes-256-cbc', key);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return iv.toString('hex') + ':' + encrypted;
};

// 密码哈希
const bcrypt = require('bcrypt');
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);

备份策略:

#!/bin/bash
# 自动备份脚本 backup.sh

# 配置
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
MYSQL_USER="backup_user"
MYSQL_PASS="backup_password"

# 创建备份目录
mkdir -p $BACKUP_DIR/mysql
mkdir -p $BACKUP_DIR/redis
mkdir -p $BACKUP_DIR/files

# MySQL备份
mysqldump -u $MYSQL_USER -p$MYSQL_PASS telegram_management > $BACKUP_DIR/mysql/backup_$DATE.sql
gzip $BACKUP_DIR/mysql/backup_$DATE.sql

# Redis备份
redis-cli --rdb $BACKUP_DIR/redis/backup_$DATE.rdb

# 文件备份
tar -czf $BACKUP_DIR/files/sessions_$DATE.tar.gz backend/sessions/
tar -czf $BACKUP_DIR/files/logs_$DATE.tar.gz backend/logs/

# 清理旧备份保留30天
find $BACKUP_DIR -type f -mtime +30 -delete

# 定时任务配置
# crontab -e
# 0 2 * * * /path/to/backup.sh

总结

本部署指南涵盖了Telegram Management System的完整部署流程包括

  1. 多种部署方式: 传统部署和Docker容器化部署
  2. 完整配置: 数据库、Redis、Web服务器等全栈配置
  3. 运维管理: 服务管理、日志管理、备份恢复
  4. 监控告警: 系统监控、性能指标、告警配置
  5. 故障排查: 常见问题及解决方案
  6. 性能优化: 数据库、缓存、应用层优化
  7. 安全加固: 系统安全、应用安全、数据安全

请根据实际环境选择合适的部署方式,并定期进行安全更新和性能优化。