Docker容器中NGINX反向代理无法正常部署React应用
问题:PWA通过NGINX反向代理无法正确加载资源
我正在协助客户开发一款PWA,这是我第一次接触该领域。本地Vite + React环境下Service Worker运行正常,但生产环境需要HTTPS才能演示。
目前无法通过NGINX反向代理正确为客户端应用提供资源服务,我配置了三个容器,相关配置如下:
Docker Compose 配置 (compose.yml)
version: '3' services: proxy: build: ./nginx-proxy ports: - 80:80 volumes: - ./nginx-proxy/nginx.conf:/etc/nginx/conf.d/default.conf networks: - my-network root: build: ./root container_name: root networks: - my-network visit: build: ./client container_name: client networks: - my-network networks: my-network:
我的需求是:root应用通过servername.com/访问,客户端应用通过servername.com/client访问。
尝试配置nginx-proxy.conf将请求转发至client容器后,资源无法加载。修改Vite基础路径后,资源看似即将加载,但出现Failed to load module script错误,我判断这是路径问题而非MIME类型问题(可能判断有误)。
以下是各容器的Dockerfile和nginx.conf配置:
反向代理容器 (./nginx-proxy)
Dockerfile
FROM nginx:latest COPY nginx.conf /etc/nginx/conf.d/nginx.conf EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
nginx.conf
server { listen 80; server_name localhost; 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-Host $server_name; location / { proxy_pass http://root; } location /visit { proxy_pass http://client; proxy_redirect off; } }
客户端应用容器 (clientapp)
Dockerfile
FROM node:18-alpine as builder WORKDIR /app COPY package.json . RUN npm i COPY . . RUN npm run build FROM nginx:1.25.1-alpine as production ENV NODE_ENV production COPY --from=builder /app/dist /usr/share/nginx/html COPY nginx.conf /etc/nginx/conf.d/default.conf EXPOSE 80 CMD [ "nginx", "-g", "daemon off;" ]
nginx.conf
server { listen 80; location / { root /usr/share/nginx/html; include /etc/nginx/mime.types; try_files $uri $uri/ /index.html; } }
React Router 配置
root和客户端应用均使用react-router-dom,我尝试为客户端应用配置basename但无效果:
const router = createBrowserRouter([ { path: "/", basename: "/client", element: <App />, errorElement: <div>Error!</div>, children: [ {index:true, element: <Home/>}, { path: "/ar", element: <AR/>}, { path: "/map", element: <Map/>}, { path: "/list", element: <List/>}, ] }, ]);
请问为何无法向浏览器正确提供资源服务?如需更多上下文信息可补充。
内容的提问来源于stack exchange,提问作者alexhowl
相关产品推荐
相关产品推荐

