Skip to content

fix: Docker 部署时前端 API 请求失败及构建缓慢卡死问题#165

Open
WinJayX wants to merge 2 commits into666ghj:mainfrom
WinJayX:fix-api-baseURL
Open

fix: Docker 部署时前端 API 请求失败及构建缓慢卡死问题#165
WinJayX wants to merge 2 commits into666ghj:mainfrom
WinJayX:fix-api-baseURL

Conversation

@WinJayX
Copy link

@WinJayX WinJayX commented Mar 12, 2026

问题描述

在使用 Docker 部署 (docker-compose up -d) 项目并在公网环境访问 Web 页面时,遇到了以下严重问题:

  1. API 请求 ERR_CONNECTION_REFUSED(Network Error)报错

    • 表现:在浏览器中访问 http://公网IP:3000/,前端页面加载正常,但控制台会报错 Network Error,无法访问后端接口。
    • 原因:前端 src/api/index.js 中的 baseURL 写死了回退地址为绝对路径 http://localhost:5001。这导致用户的浏览器加载页面后,会尝试去请求**用户自己电脑(localhost)**上的 5001 端口,而不是服务器 Docker 容器里的 5001 端口。因为跨域和本机无服务的双重原因,所有的 API 请求全部被拒绝。
  2. 构建镜像极度缓慢甚至长时卡死

    • 表现:在服务器上执行 docker-compose build 时,经常卡在 => FROM ghcr.io/astral-sh/uv:0.9.26... 长达数分钟甚至失败。
    • 原因:国内网络拉取 ghcr.io (GitHub Container Registry) 镜像非常不稳定。此外,后续的 npm ci 和 uv sync 过程也没有配置国内镜像加速源,导致构建过程十分痛苦。
  3. spawn xdg-open ENOENT 报错干扰

    • 表现:容器日志(docker-compose logs)中经常输出这个错误。
    • 原因:frontend/vite.config.js 启用了 open: true,Vite 会尝试打开浏览器,但 Docker 容器内并无桌面和 xdg-open 环境产生的报错。

修复说明

  1. 移除 frontend/src/api/index.js 中的 fallback http://localhost:5001,将其改为空字符串 ''

    • 效果:axios 现在的请求变成了相对路径(例如 /api/simulation/history),这会让请求发给当前的来源 URL(比如 http://公网IP:3000/api/...),然后 Vite dev server 的 proxy 机制就能在容器内部正常把 /api 转发给 Flask 后端(localhost:5001)。彻底解决了 Docker 部署下的联通性问题。
  2. 优化 Dockerfile 中针对国内网络的构建流程(提速显著):

    • 取消通过 COPY --from=ghcr.io/astral-sh/uv 直接拉取镜像。
    • 替换为:RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ uv,使用阿里云 Pypi 源秒速安装 uv。
    • npm 预先配置:npm config set registry https://registry.npmmirror.com,使用淘宝镜像秒速拉取前端构建包。
    • Python 构建源:在使用 uv 同步后端时,追加环境变量 env UV_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ uv sync --frozen,使用阿里源加速 Python 包下载。
    • 添加 Debian 国内源,加速 nodejs 的安装。
  3. 移除 frontend/vite.config.jsopen: true,消除不必要的控制台报错。

WinJayX added 2 commits March 12, 2026 15:48
This fixes the issue where the frontend in docker tries to connect to localhost instead of the Vite proxy.
Replace ghcr.io/astral-sh/uv with pip install using aliyun mirror to prevent hanging. Also configure npm and uv to use domestic registry/mirror.
@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Mar 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant