Search-Goods/.trae/documents/在 Ubuntu 22.04(宝塔面板)部署商品查询系统的方案.md

86 lines
3.9 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.

## 总览
- 目标:在 Ubuntu 22.04(装有宝塔面板)部署现有 FastAPI + SQLite 项目,绑定域名并启用 HTTPS支持前端查询与 Excel 导入。
- 推荐路径:使用宝塔 Nginx 站点做反向代理,后端用虚拟环境 + `uvicorn` 常驻systemd或使用宝塔的 Python 项目插件;也可选 Docker 方案。
## 路径APython 虚拟环境 + systemd + Nginx 反代(稳定通用)
1. 上传项目到服务器
- 位置:`/www/wwwroot/product-query`(宝塔默认网站目录)
- 结构:包含 `app/`、`static/`、`requirements.txt`、`scripts/`、`README.md`
2. 安装依赖并准备运行目录
- `sudo apt update && sudo apt install -y python3.10-venv`22.04 默认 Python3.10
- `cd /www/wwwroot/product-query`
- `python3 -m venv venv && source venv/bin/activate`
- `pip install -r requirements.txt`
- `mkdir -p data && chown -R www:www /www/wwwroot/product-query`
3. 创建 systemd 服务
- 新建 `/etc/systemd/system/product-query.service`
```
[Unit]
Description=Product Query FastAPI
After=network.target
[Service]
WorkingDirectory=/www/wwwroot/product-query
ExecStart=/www/wwwroot/product-query/venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 9000
Restart=always
User=www
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
```
- 执行:`sudo systemctl daemon-reload && sudo systemctl enable product-query && sudo systemctl start product-query && sudo systemctl status product-query`
4. 宝塔创建网站并配置反向代理
- 在宝塔面板 → 网站 → 添加站点,绑定你的域名(示例 `query.example.com`
- 在该站点的“反向代理”中设置:
- 目标地址:`http://127.0.0.1:9000`
- 开启“缓存/压力测试”时先关闭,调试稳定后再按需开启
- SSL在站点的“SSL”中申请 Lets Encrypt 并开启强制 HTTPS
5. 验证
- `curl http://127.0.0.1:9000/health` 返回 `{"status":"ok"}`
- 访问 `https://query.example.com/` 打开前端页面
## 路径B宝塔 Python 项目插件(图形化管理)
1. 在宝塔应用商店安装“Python 项目管理器”(版本需支持 FastAPI/uvicorn
2. 新建项目:
- 运行目录:`/www/wwwroot/product-query`
- 选择 Python 解释器或创建虚拟环境
- 安装依赖:在插件里执行 `pip install -r requirements.txt`
- 启动命令:`uvicorn app.main:app --host 127.0.0.1 --port 9000`
- 日志路径与守护设置按需配置
3. 按路径A第4步在 Nginx 站点做反向代理与 SSL
## 路径CDocker / Compose面板或命令行皆可
1. 安装 Docker 与 Compose或使用宝塔 Docker 管理器)
- `sudo apt install -y docker.io docker-compose`
2. 在项目目录执行:
- `docker compose up -d`(使用仓库内 `docker-compose.yml`
- 容器监听 `8000`,宿主机映射 `8000:8000`,数据持久化到宿主 `./data`
3. 在宝塔 Nginx 站点反代到 `127.0.0.1:8000` 并配置 SSL
## 数据与权限
- 数据库存放在 `data/products.db`,务必保留该目录的持久化
- 权限建议:`chown -R www:www /www/wwwroot/product-query`,确保 Nginx/反代用户读写正常(写入仅限后端进程)
## 运维与排错
- 服务日志:
- systemd`journalctl -u product-query -f`
- Python插件/Docker在面板或 `docker logs -f product-query`
- 常见问题:
- 反代 502检查后端是否启动、端口是否匹配、站点安全组/防火墙是否放行
- 中文编码:浏览器显示正常;命令行可能乱码,不影响功能
## 上线Checklist
- 站点域名与反向代理已配置
- SSL 已启用且强制跳转 HTTPS
- 后端进程已常驻systemd 或插件守护)
- `/import` 上传上限:在 Nginx/站点上传限制按需提高(如 50MB
- 防火墙安全:只开放 80/443后端端口用 127.0.0.1 回环
## 你需准备的信息
- 目标域名(如需绑定)
- 选择的部署路径A/B/C我可以据此输出一键命令与面板操作截图式步骤