# 知识库系统部署指南

本文档提供知识库系统的详细部署步骤和配置说明。

## 目录

1. [服务器要求](#服务器要求)
2. [安装依赖](#安装依赖)
3. [项目部署](#项目部署)
4. [配置服务](#配置服务)
5. [性能优化](#性能优化)
6. [监控和维护](#监控和维护)
7. [故障排除](#故障排除)

## 服务器要求

### 最低配置
- **CPU**: 2 核心
- **内存**: 4GB RAM
- **存储**: 50GB SSD
- **操作系统**: Ubuntu 20.04+ / CentOS 8+ / Debian 11+

### 推荐配置
- **CPU**: 4 核心
- **内存**: 8GB RAM
- **存储**: 100GB SSD
- **操作系统**: Ubuntu 22.04 LTS

### 软件要求
- PHP 8.1 或更高版本
- MySQL 8.0+ 或 PostgreSQL 13+
- Redis 6.0+
- Nginx 1.18+ 或 Apache 2.4+
- Composer 2.x
- Node.js 18+ 和 npm
- Meilisearch 1.5+
- Pandoc 2.x+（用于文档转换）
- Supervisor（用于管理队列进程）

## 安装依赖

### 1. 安装 PHP 和扩展

#### Ubuntu/Debian
```bash
sudo apt update
sudo apt install -y php8.1 php8.1-fpm php8.1-cli php8.1-common \
    php8.1-mysql php8.1-pgsql php8.1-redis php8.1-xml php8.1-mbstring \
    php8.1-curl php8.1-zip php8.1-gd php8.1-intl php8.1-bcmath
```

#### CentOS/RHEL
```bash
sudo dnf install -y php php-fpm php-cli php-common php-mysqlnd \
    php-pgsql php-redis php-xml php-mbstring php-curl php-zip \
    php-gd php-intl php-bcmath
```

### 2. 安装 Composer

```bash
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer
```

### 3. 安装 Node.js 和 npm

```bash
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
```

### 4. 安装 MySQL

```bash
sudo apt install -y mysql-server
sudo mysql_secure_installation
```

创建数据库和用户：

```sql
CREATE DATABASE knowledge_base CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'kb_user'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON knowledge_base.* TO 'kb_user'@'localhost';
FLUSH PRIVILEGES;
```

### 5. 安装 Redis

```bash
sudo apt install -y redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server
```

### 6. 安装 Meilisearch

#### 使用 Docker（推荐）
```bash
docker run -d \
  --name meilisearch \
  -p 7700:7700 \
  -v $(pwd)/storage/meilisearch:/meili_data \
  -e MEILI_MASTER_KEY='your_master_key_here' \
  getmeili/meilisearch:v1.5
```

#### 直接安装
```bash
curl -L https://install.meilisearch.com | sh
sudo mv ./meilisearch /usr/local/bin/
```

创建 systemd 服务：

```bash
sudo nano /etc/systemd/system/meilisearch.service
```

内容：

```ini
[Unit]
Description=Meilisearch
After=network.target

[Service]
Type=simple
User=www-data
ExecStart=/usr/local/bin/meilisearch --master-key="your_master_key_here" --db-path=/var/lib/meilisearch/data
Restart=on-failure

[Install]
WantedBy=multi-user.target
```

启动服务：

```bash
sudo systemctl daemon-reload
sudo systemctl enable meilisearch
sudo systemctl start meilisearch
```

### 7. 安装 Pandoc

```bash
sudo apt install -y pandoc
```

或下载最新版本：

```bash
wget https://github.com/jgm/pandoc/releases/download/3.1.11/pandoc-3.1.11-1-amd64.deb
sudo dpkg -i pandoc-3.1.11-1-amd64.deb
```

### 8. 安装 Supervisor

```bash
sudo apt install -y supervisor
sudo systemctl enable supervisor
sudo systemctl start supervisor
```

## 项目部署

### 1. 克隆项目

```bash
cd /var/www
sudo git clone <repository-url> knowledge-base
cd knowledge-base
```

### 2. 设置权限

```bash
sudo chown -R www-data:www-data /var/www/knowledge-base
sudo chmod -R 755 /var/www/knowledge-base
sudo chmod -R 775 /var/www/knowledge-base/storage
sudo chmod -R 775 /var/www/knowledge-base/bootstrap/cache
```

### 3. 安装依赖

```bash
# PHP 依赖
composer install --no-dev --optimize-autoloader

# 前端依赖
npm install
npm run build
```

### 4. 配置环境变量

```bash
cp .env.example .env
nano .env
```

配置以下关键参数：

```env
APP_NAME="知识库系统"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://your-domain.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=knowledge_base
DB_USERNAME=kb_user
DB_PASSWORD=your_secure_password

CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=your_master_key_here
SCOUT_DRIVER=meilisearch

DOCUMENT_CONVERSION_DRIVER=pandoc
PANDOC_PATH=/usr/bin/pandoc
CONVERSION_TIMEOUT=300

FILESYSTEM_DISK=local
```

### 5. 生成应用密钥

```bash
php artisan key:generate
```

### 6. 运行数据库迁移

```bash
php artisan migrate --force
```

### 7. 创建存储目录

```bash
mkdir -p storage/app/private/documents
mkdir -p storage/app/private/markdown
sudo chown -R www-data:www-data storage/app/private
sudo chmod -R 775 storage/app/private
```

### 8. 优化应用

```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan filament:optimize
```

### 9. 创建管理员用户

```bash
php artisan make:filament-user
```

## 配置服务

### 1. 配置 Nginx

创建站点配置：

```bash
sudo nano /etc/nginx/sites-available/knowledge-base
```

内容：

```nginx
server {
    listen 80;
    listen [::]:80;
    server_name your-domain.com;
    root /var/www/knowledge-base/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    # 文件上传大小限制
    client_max_body_size 50M;
}
```

启用站点：

```bash
sudo ln -s /etc/nginx/sites-available/knowledge-base /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

### 2. 配置 SSL（使用 Let's Encrypt）

```bash
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com
```

### 3. 配置队列工作进程

创建 Supervisor 配置：

```bash
sudo nano /etc/supervisor/conf.d/knowledge-base-worker.conf
```

内容：

```ini
[program:knowledge-base-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/knowledge-base/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/knowledge-base/storage/logs/worker.log
stopwaitsecs=3600
```

重新加载 Supervisor：

```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start knowledge-base-worker:*
```

### 4. 配置定时任务

编辑 crontab：

```bash
sudo crontab -e -u www-data
```

添加：

```cron
* * * * * cd /var/www/knowledge-base && php artisan schedule:run >> /dev/null 2>&1
```

## 性能优化

### 1. PHP-FPM 优化

编辑 PHP-FPM 配置：

```bash
sudo nano /etc/php/8.1/fpm/pool.d/www.conf
```

调整参数：

```ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
pm.max_requests = 500
```

重启 PHP-FPM：

```bash
sudo systemctl restart php8.1-fpm
```

### 2. Redis 优化

编辑 Redis 配置：

```bash
sudo nano /etc/redis/redis.conf
```

调整参数：

```conf
maxmemory 2gb
maxmemory-policy allkeys-lru
```

重启 Redis：

```bash
sudo systemctl restart redis-server
```

### 3. MySQL 优化

编辑 MySQL 配置：

```bash
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
```

添加优化参数：

```ini
[mysqld]
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
query_cache_size = 0
query_cache_type = 0
```

重启 MySQL：

```bash
sudo systemctl restart mysql
```

### 4. Opcache 配置

编辑 PHP 配置：

```bash
sudo nano /etc/php/8.1/fpm/conf.d/10-opcache.ini
```

内容：

```ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
```

## 监控和维护

### 1. 日志监控

查看应用日志：

```bash
tail -f /var/www/knowledge-base/storage/logs/laravel.log
```

查看队列工作进程日志：

```bash
tail -f /var/www/knowledge-base/storage/logs/worker.log
```

查看 Nginx 日志：

```bash
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
```

### 2. 定期备份

#### 数据库备份

创建备份脚本：

```bash
sudo nano /usr/local/bin/backup-kb-db.sh
```

内容：

```bash
#!/bin/bash
BACKUP_DIR="/var/backups/knowledge-base"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

mysqldump -u kb_user -p'your_secure_password' knowledge_base | gzip > $BACKUP_DIR/db_$DATE.sql.gz

# 保留最近 7 天的备份
find $BACKUP_DIR -name "db_*.sql.gz" -mtime +7 -delete
```

设置权限并添加到 crontab：

```bash
sudo chmod +x /usr/local/bin/backup-kb-db.sh
sudo crontab -e
```

添加每日备份任务：

```cron
0 2 * * * /usr/local/bin/backup-kb-db.sh
```

#### 文件备份

```bash
sudo nano /usr/local/bin/backup-kb-files.sh
```

内容：

```bash
#!/bin/bash
BACKUP_DIR="/var/backups/knowledge-base"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

tar -czf $BACKUP_DIR/files_$DATE.tar.gz \
    /var/www/knowledge-base/storage/app/private/documents \
    /var/www/knowledge-base/storage/app/private/markdown

# 保留最近 7 天的备份
find $BACKUP_DIR -name "files_*.tar.gz" -mtime +7 -delete
```

### 3. 系统监控

安装监控工具：

```bash
sudo apt install -y htop iotop nethogs
```

监控系统资源：

```bash
# CPU 和内存
htop

# 磁盘 I/O
iotop

# 网络流量
nethogs
```

### 4. 应用健康检查

创建健康检查脚本：

```bash
sudo nano /usr/local/bin/check-kb-health.sh
```

内容：

```bash
#!/bin/bash

# 检查 Web 服务
if ! curl -f http://localhost > /dev/null 2>&1; then
    echo "Web service is down!"
    sudo systemctl restart nginx
fi

# 检查队列工作进程
if ! sudo supervisorctl status knowledge-base-worker:* | grep RUNNING > /dev/null; then
    echo "Queue worker is down!"
    sudo supervisorctl restart knowledge-base-worker:*
fi

# 检查 Meilisearch
if ! curl -f http://localhost:7700/health > /dev/null 2>&1; then
    echo "Meilisearch is down!"
    sudo systemctl restart meilisearch
fi
```

添加到 crontab（每 5 分钟检查一次）：

```cron
*/5 * * * * /usr/local/bin/check-kb-health.sh
```

## 故障排除

### 1. 文件上传失败

检查 PHP 配置：

```bash
php -i | grep upload_max_filesize
php -i | grep post_max_size
```

如需调整，编辑 PHP 配置：

```bash
sudo nano /etc/php/8.1/fpm/php.ini
```

修改：

```ini
upload_max_filesize = 50M
post_max_size = 50M
```

重启 PHP-FPM：

```bash
sudo systemctl restart php8.1-fpm
```

### 2. 队列任务不执行

检查队列工作进程状态：

```bash
sudo supervisorctl status knowledge-base-worker:*
```

重启工作进程：

```bash
sudo supervisorctl restart knowledge-base-worker:*
```

查看队列日志：

```bash
tail -f /var/www/knowledge-base/storage/logs/worker.log
```

### 3. Meilisearch 连接失败

检查 Meilisearch 状态：

```bash
curl http://localhost:7700/health
```

检查 Meilisearch 日志：

```bash
sudo journalctl -u meilisearch -f
```

重启 Meilisearch：

```bash
sudo systemctl restart meilisearch
```

### 4. 文档转换失败

检查 Pandoc 是否安装：

```bash
which pandoc
pandoc --version
```

检查转换日志：

```bash
grep "conversion" /var/www/knowledge-base/storage/logs/laravel.log
```

手动测试转换：

```bash
pandoc test.docx -o test.md
```

### 5. 权限问题

重置存储目录权限：

```bash
cd /var/www/knowledge-base
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache
```

### 6. 缓存问题

清除所有缓存：

```bash
cd /var/www/knowledge-base
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
```

重新生成缓存：

```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

## 更新部署

### 1. 拉取最新代码

```bash
cd /var/www/knowledge-base
sudo -u www-data git pull origin main
```

### 2. 更新依赖

```bash
sudo -u www-data composer install --no-dev --optimize-autoloader
sudo -u www-data npm install
sudo -u www-data npm run build
```

### 3. 运行迁移

```bash
php artisan migrate --force
```

### 4. 清除和重建缓存

```bash
php artisan cache:clear
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan filament:optimize
```

### 5. 重启服务

```bash
sudo systemctl reload php8.1-fpm
sudo systemctl reload nginx
sudo supervisorctl restart knowledge-base-worker:*
```

## 安全建议

1. **定期更新系统和软件包**
```bash
sudo apt update && sudo apt upgrade -y
```

2. **配置防火墙**
```bash
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```

3. **禁用不必要的 PHP 函数**
编辑 `php.ini`，添加：
```ini
disable_functions = exec,passthru,shell_exec,system,proc_open,popen
```

4. **设置强密码策略**
5. **定期审查安全日志**
6. **启用 HTTPS**
7. **限制文件上传类型**
8. **定期备份数据**

## 联系支持

如遇到部署问题，请联系技术支持团队。

---

**最后更新**：2025-12-05
