Files
nxxmdata/docs/TROUBLESHOOTING.md

795 lines
14 KiB
Markdown
Raw Normal View History

# 故障排除指南
## 概述
本文档提供宁夏智慧养殖监管平台常见问题的诊断和解决方案,帮助开发人员和运维人员快速定位和解决系统故障。
## 目录
- [环境相关问题](#环境相关问题)
- [数据库问题](#数据库问题)
- [API服务问题](#api服务问题)
- [前端问题](#前端问题)
- [性能问题](#性能问题)
- [部署问题](#部署问题)
- [日志分析](#日志分析)
- [监控和诊断工具](#监控和诊断工具)
## 环境相关问题
### Node.js 版本问题
**问题症状:**
```bash
Error: The engine "node" is incompatible with this module
```
**解决方案:**
```bash
# 检查当前 Node.js 版本
node --version
# 要求版本: Node.js 18.0+
# 升级 Node.js
nvm install 18
nvm use 18
# 或者使用官方安装包
# https://nodejs.org/
```
### npm 依赖安装失败
**问题症状:**
```bash
npm ERR! peer dep missing
npm ERR! network timeout
```
**解决方案:**
```bash
# 1. 清理缓存
npm cache clean --force
# 2. 删除 node_modules 和 package-lock.json
rm -rf node_modules package-lock.json
# 3. 重新安装
npm install
# 4. 如果网络问题,使用国内镜像
npm config set registry https://registry.npmmirror.com/
# 5. 使用 yarn 替代
yarn install
```
### 环境变量配置问题
**问题症状:**
```bash
Error: Missing required environment variable
```
**解决方案:**
```bash
# 1. 检查 .env 文件是否存在
ls -la .env
# 2. 复制示例配置文件
cp .env.example .env
# 3. 编辑配置文件
nano .env
# 4. 验证环境变量
node -e "console.log(process.env.DB_HOST)"
```
## 数据库问题
### 数据库连接失败
**问题症状:**
```
Error: connect ECONNREFUSED 127.0.0.1:3306
SequelizeConnectionError: Access denied for user
```
**诊断步骤:**
```bash
# 1. 检查 MySQL 服务状态
# macOS
brew services list | grep mysql
# Linux
systemctl status mysql
# Windows
net start mysql
# 2. 测试数据库连接
mysql -u root -p -h localhost -P 3306
# 3. 检查端口占用
lsof -i :3306
netstat -an | grep 3306
```
**解决方案:**
```bash
# 1. 启动 MySQL 服务
# macOS
brew services start mysql
# Linux
sudo systemctl start mysql
# Windows
net start mysql
# 2. 重置 MySQL 密码
mysql -u root -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
FLUSH PRIVILEGES;
# 3. 创建数据库用户
CREATE USER 'nxxmdata_user'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON nxxmdata.* TO 'nxxmdata_user'@'localhost';
FLUSH PRIVILEGES;
```
### 数据库迁移失败
**问题症状:**
```
Migration failed: Table already exists
Sequelize migration error
```
**解决方案:**
```bash
# 1. 检查迁移状态
cd backend
npm run db:status
# 2. 回滚迁移
npm run db:rollback
# 3. 强制重置数据库(谨慎使用)
mysql -u root -p
DROP DATABASE nxxmdata;
CREATE DATABASE nxxmdata CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
# 4. 重新运行迁移
npm run db:migrate
```
### 数据不一致问题
**问题症状:**
```
Foreign key constraint fails
Data validation errors
```
**诊断脚本:**
```bash
cd backend
# 检查外键约束
node check-orphaned-foreign-keys.js
# 检查数据完整性
node verify-data.js
# 检查表结构
node check-table-structure.js
```
**解决方案:**
```bash
# 修复孤立外键
node fix-orphaned-foreign-keys.js
# 重新排序主键
node reorder-primary-keys.js
# 验证修复结果
node verify-data.js
```
## API服务问题
### 服务启动失败
**问题症状:**
```bash
Error: listen EADDRINUSE :::5350
Cannot find module
```
**解决方案:**
```bash
# 1. 检查端口占用
lsof -i :5350
netstat -tulpn | grep 5350
# 2. 杀死占用进程
kill -9 <PID>
# 3. 更换端口
export PORT=5351
npm run dev
# 4. 检查模块依赖
npm install
npm audit fix
```
### JWT Token 问题
**问题症状:**
```
401 Unauthorized
Token expired
Invalid token
```
**解决方案:**
```bash
# 1. 检查 JWT 密钥配置
echo $JWT_SECRET
# 2. 验证 Token 格式
node -e "console.log(require('jsonwebtoken').verify('YOUR_TOKEN', 'YOUR_SECRET'))"
# 3. 重新生成密钥
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
```
### API 响应慢
**问题症状:**
```
Response time > 5000ms
Timeout errors
```
**诊断工具:**
```bash
# 1. 检查数据库查询性能
cd backend
node utils/query-optimizer.js
# 2. 查看性能监控
curl http://localhost:5350/api/performance/metrics
# 3. 分析慢查询日志
tail -f logs/performance/database-YYYY-MM-DD.log
```
**优化方案:**
```javascript
// 1. 添加数据库索引
CREATE INDEX idx_farms_status ON farms(status);
CREATE INDEX idx_devices_farm_id ON devices(farm_id);
// 2. 优化查询语句
const farms = await Farm.findAll({
attributes: ['id', 'name', 'status'], // 只查询需要的字段
include: [{
model: Device,
attributes: ['id', 'status']
}],
limit: 10,
offset: (page - 1) * 10
});
// 3. 使用缓存
const Redis = require('redis');
const redis = Redis.createClient();
```
## 前端问题
### 构建失败
**问题症状:**
```bash
Build failed with errors
Module not found
Syntax error in code
```
**解决方案:**
```bash
# 1. 清理构建缓存
cd admin-system/frontend
rm -rf node_modules/.vite
rm -rf dist
# 2. 检查依赖版本
npm ls
# 3. 更新依赖
npm update
# 4. 重新构建
npm run build
```
### 路由问题
**问题症状:**
```
404 Page not found
Router navigation errors
```
**解决方案:**
```javascript
// 1. 检查路由配置
// router/routes.js
export const routes = [
{
path: '/',
redirect: '/dashboard'
},
{
path: '/farms',
component: () => import('../views/Farms.vue')
}
];
// 2. 检查 Nginx 配置
// location / {
// try_files $uri $uri/ /index.html;
// }
```
### API 调用失败
**问题症状:**
```
CORS errors
Network errors
401/403 errors
```
**解决方案:**
```javascript
// 1. 检查 API 基础 URL
// config/env.js
export const API_BASE_URL = process.env.VITE_API_BASE_URL || 'http://localhost:5350/api';
// 2. 添加请求拦截器
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// 3. 处理响应错误
axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// 清除 token跳转到登录页
localStorage.removeItem('token');
router.push('/login');
}
return Promise.reject(error);
}
);
```
### 地图显示问题
**问题症状:**
```
百度地图加载失败
地图空白
坐标偏移
```
**解决方案:**
```javascript
// 1. 检查 API 密钥
console.log('百度地图 API Key:', process.env.VITE_BAIDU_MAP_API_KEY);
// 2. 验证域名白名单
// 登录百度地图开放平台控制台检查 Referer 设置
// 3. 检查坐标系统
// 确保使用 BD09 坐标系
const point = new BMap.Point(106.26667, 38.46667);
// 4. 处理坐标转换
// 如果数据是 WGS84 或 GCJ02需要转换为 BD09
```
## 性能问题
### 内存泄漏
**问题症状:**
```
Memory usage keeps growing
Process killed by system
```
**诊断工具:**
```bash
# 1. 监控内存使用
node --inspect server.js
# 打开 Chrome DevTools -> Memory 选项卡
# 2. 使用 clinic.js
npm install -g clinic
clinic doctor -- node server.js
# 3. 使用 PM2 监控
pm2 install pm2-server-monit
pm2 monit
```
**解决方案:**
```javascript
// 1. 清理事件监听器
process.removeAllListeners('exit');
// 2. 关闭数据库连接
await sequelize.close();
// 3. 限制并发请求
const pLimit = require('p-limit');
const limit = pLimit(10);
// 4. 使用对象池
const pool = new Pool({
create: () => new ExpensiveObject(),
destroy: (obj) => obj.cleanup()
});
```
### CPU 使用率高
**问题症状:**
```
CPU usage > 80%
Response time degradation
```
**诊断方法:**
```bash
# 1. 查看进程状态
top -p $(pgrep node)
htop
# 2. 分析性能瓶颈
node --prof server.js
node --prof-process isolate-*.log > processed.txt
# 3. 使用火焰图
npm install -g 0x
0x server.js
```
### 数据库查询慢
**问题症状:**
```
Query execution time > 1000ms
Database connection pool exhausted
```
**优化策略:**
```sql
-- 1. 添加索引
EXPLAIN SELECT * FROM farms WHERE status = 'active';
CREATE INDEX idx_farms_status ON farms(status);
-- 2. 优化查询
-- 避免 SELECT *
SELECT id, name, status FROM farms WHERE status = 'active';
-- 3. 使用查询缓存
SET SESSION query_cache_type = ON;
```
## 部署问题
### Docker 构建失败
**问题症状:**
```
Docker build failed
Image size too large
Container startup errors
```
**解决方案:**
```dockerfile
# 1. 优化 Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
# 2. 使用多阶段构建
FROM node:18-alpine AS runner
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 5350
CMD ["npm", "start"]
# 3. 添加 .dockerignore
node_modules
.git
.env
logs/*
```
### Nginx 配置问题
**问题症状:**
```
502 Bad Gateway
404 for static files
CORS errors
```
**解决方案:**
```nginx
server {
listen 80;
server_name localhost;
# 解决 CORS 问题
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "Content-Type, Authorization";
# 前端路由
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ /index.html;
}
# API 代理
location /api {
proxy_pass http://backend:5350;
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_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
}
```
### SSL 证书问题
**问题症状:**
```
Certificate expired
SSL handshake failed
Mixed content warnings
```
**解决方案:**
```bash
# 1. 使用 Let's Encrypt
certbot --nginx -d yourdomain.com
# 2. 检查证书状态
openssl x509 -in /path/to/cert.pem -text -noout
# 3. 自动续期
echo "0 12 * * * /usr/bin/certbot renew --quiet" | crontab -
# 4. 强制 HTTPS
return 301 https://$server_name$request_uri;
```
## 日志分析
### 后端日志
**日志位置:**
```bash
backend/logs/
├── app.log # 应用日志
├── error.log # 错误日志
├── access.log # 访问日志
└── performance/ # 性能监控日志
├── system-YYYY-MM-DD.log
└── database-YYYY-MM-DD.log
```
**常用命令:**
```bash
# 实时查看日志
tail -f backend/logs/app.log
# 搜索错误
grep -i error backend/logs/*.log
# 分析访问模式
awk '{print $1}' backend/logs/access.log | sort | uniq -c | sort -nr
# 查看特定时间段日志
sed -n '/2025-01-18 10:00/,/2025-01-18 11:00/p' backend/logs/app.log
```
### 前端日志
**浏览器控制台:**
```javascript
// 1. 查看网络请求
// Network 标签页 -> 筛选 XHR/Fetch
// 2. 查看 JavaScript 错误
// Console 标签页 -> 筛选 Errors
// 3. 查看性能
// Performance 标签页 -> 录制并分析
// 4. 查看内存使用
// Memory 标签页 -> Heap snapshot
```
## 监控和诊断工具
### 系统监控
```bash
# 1. 系统资源监控
htop
iostat -x 1
vmstat 1
# 2. 磁盘使用
df -h
du -sh /path/to/project
# 3. 网络连接
netstat -tulpn
ss -tulpn
```
### 应用监控
```bash
# 1. PM2 监控
pm2 monit
pm2 logs
pm2 show app-name
# 2. Node.js 性能分析
node --inspect server.js
# 访问 chrome://inspect
# 3. 数据库监控
SHOW PROCESSLIST;
SHOW STATUS LIKE 'Slow_queries';
```
### 自定义监控脚本
```bash
#!/bin/bash
# health-check.sh
# 检查服务状态
curl -f http://localhost:5350/api/health || echo "API 服务异常"
# 检查数据库连接
mysql -u root -p -e "SELECT 1" > /dev/null 2>&1 || echo "数据库连接失败"
# 检查磁盘空间
df -h | awk '$5 > 80 {print "磁盘使用率过高: " $0}'
# 检查内存使用
free | awk 'NR==2{printf "内存使用率: %.2f%%\n", $3*100/$2}'
```
## 紧急响应流程
### 服务不可用
**立即响应 (5分钟内):**
```bash
# 1. 检查服务状态
pm2 status
systemctl status nginx
# 2. 重启服务
pm2 restart all
systemctl restart nginx
# 3. 检查日志
tail -f logs/error.log
```
**深入分析 (30分钟内):**
```bash
# 1. 检查系统资源
top
df -h
free -h
# 2. 分析错误日志
grep -i error logs/*.log | tail -20
# 3. 数据库健康检查
mysql -e "SHOW PROCESSLIST;"
```
### 数据库异常
**紧急处理:**
```bash
# 1. 检查数据库状态
systemctl status mysql
# 2. 查看错误日志
tail -f /var/log/mysql/error.log
# 3. 重启数据库服务
systemctl restart mysql
# 4. 检查数据完整性
mysqlcheck -u root -p --all-databases
```
### 安全事件
**响应步骤:**
```bash
# 1. 隔离受影响的服务
pm2 stop suspicious-process
# 2. 检查访问日志
grep -E "(404|500)" logs/access.log | tail -50
# 3. 更新密码和密钥
# 重新生成 JWT 密钥
# 强制所有用户重新登录
# 4. 通知相关人员
echo "安全事件发生,请立即检查系统" | mail -s "紧急: 安全告警" admin@company.com
```
## 联系支持
### 获取帮助的渠道
1. **技术支持邮箱**: support@nxxmdata.com
2. **紧急联系电话**: 400-xxx-xxxx
3. **在线文档**: https://docs.nxxmdata.com
4. **GitHub Issues**: https://github.com/your-org/nxxmdata/issues
### 报告问题时请提供
1. **错误描述**: 详细的错误信息和复现步骤
2. **环境信息**: 操作系统、Node.js版本、浏览器版本
3. **日志文件**: 相关的错误日志
4. **配置信息**: 去敏感化的配置文件
5. **系统状态**: CPU、内存、磁盘使用情况
---
*最后更新: 2025年1月*
**注意**: 本文档会根据系统更新持续完善,请定期查看最新版本。