Files
wecom_it_smart_desk/docs/09-部署运维/deploy/502-BadGateway-后端启动失败-20260705.md
T

121 lines
2.7 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.
# 502 Bad Gateway - 后端启动失败
> 日期:2026-07-05
> 问题:坐席端登录失败,返回 502 Bad Gateway
---
## 一、问题现象
用户访问 `https://itsupport.servyou.com.cn/itagent/` 时提示登录失败:
```
Failed to load resource: the server responded with a status of 502 (Bad Gateway)
AxiosError: Request failed with status code 502
```
---
## 二、诊断过程
### 2.1 检查容器状态
```bash
docker ps -a
```
发现后端容器状态为 `unhealthy`
```
CONTAINER ID IMAGE STATUS
656f7696d4e5 wecom-it-desk-backend:latest Up 8 minutes (unhealthy)
```
### 2.2 检查后端日志
```bash
docker logs 656f7696d4e5 --tail 30
```
发现错误:
```
ModuleNotFoundError: No module named 'aioredis'
```
### 2.3 原因分析
- 旧版镜像中代码使用 `import aioredis`
-`aioredis` 包与 Python 3.12 不兼容
- 报错:`TypeError: duplicate base class TimeoutError`
---
## 三、解决方案
### 3.1 尝试修复(失败)
尝试在容器内安装 `aioredis` 包,但发现:
- `aioredis` 与 Python 3.12 不兼容
- 安装后仍报错:`TypeError: duplicate base class TimeoutError`
### 3.2 最终方案
删除旧容器,使用正确的环境变量重新启动:
```bash
# 1. 删除旧容器
docker stop 656f7696d4e5
docker rm 656f7696d4e5
# 2. 使用正确的 PYTHONPATH 重新启动
cd /opt/wecom-it-desk
PYTHONPATH=/app docker compose up -d backend
```
关键点:**必须设置 `PYTHONPATH=/app`**,否则会报错 `ModuleNotFoundError: No module named 'app.core'`
---
## 四、验证结果
```bash
# 检查容器状态
docker ps
# 输出:
# 2ec80dee024c wecom-it-desk-backend:latest Up 5 minutes (healthy)
# e147524342fa redis:7-alpine Up 11 hours (healthy)
# 8a2265864f34 nginx:1.27-alpine Up 11 hours
# 433ef922c8d8 postgres:16-alpine Up 11 hours (healthy)
# 测试 API
curl http://localhost:8000/health
# 输出:{"status":"ok"}
# 测试页面
curl -sk https://localhost/itdesk/
# 输出:HTML 页面正常返回
```
---
## 五、根因总结
| 问题 | 原因 |
|------|------|
| 后端容器 unhealthy | 旧镜像使用 `import aioredis`,与 Python 3.12 不兼容 |
| 启动失败 | 需要设置 `PYTHONPATH=/app` 环境变量 |
---
## 六、预防措施
1. **更新镜像**:在 Dockerfile 中将所有 `import aioredis` 改为 `import redis.asyncio as aioredis`
2. **环境变量**:确保 docker-compose.yml 中设置 `PYTHONPATH=/app`
3. **健康检查**:定期检查容器健康状态
---
## 七、相关文件
- 部署配置:`/opt/wecom-it-desk/docker-compose.yml`
- Nginx 配置:`/opt/wecom-it-desk/nginx/nginx.conf`
- 后端代码:`/opt/wecom-it-desk/backend/`