首页 > 解决方案 > React Application 在使用 NGINX 时只显示 public/index.html

问题描述

我正在尝试将带有 Docker 的 React 应用程序部署到 Nginx 映像。

目前,一旦构建完成并运行 Docker,我可以通过 访问该页面localhost:xxxx,但仅public/index.html显示我的 React 应用程序中的内容(即 favicon、站点标题),而没有其他内容显示。

注意,运行npm start显示页面没有任何问题。

以下是我的 React 应用程序的 、 和一般结构供参考Dockerfilenginx.conf

Dockerfile

FROM node:14.7-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./
RUN npm install --silent
RUN npm install react-scripts@3.4.1 -g --silent
COPY . ./
RUN npm run build

FROM nginx:1.16.0-alpine
COPY --from=build /app/build /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
   server_name test-frontend;

   location / {
      root /usr/share/nginx/html;
      index index.html index.htm;
      try_files $uri /index.html;
   }

   error_page 500 502 503 504 /50x.html;

   location = /50x.html {
      root /usr/share/nginx/html;
   }
}

React 应用结构

test-frontend/
├── Dockerfile
├── .dockerignore
├── jsconfig.json
├── nginx.conf
├── npm-debug.log
├── package.json
├── package-lock.json
├── nodemodules/
  ├── package/
  │   ├── ...
  │   ├── ...
  │   ├── ...
  └── .../
├── public/
  ├── favicon.ico
  ├── icon.png
  ├── index.html <--- this loads fine.
  ├── manifest.json
├── src/
  ├── assets/
  ├── components/
  ├── views/
  ├── index.js <--- this does not populate.
  ├── routes.js <--- routes are ignored.

任何帮助将不胜感激。

标签: reactjsdockernginxdocker-composereact-router

解决方案


推荐阅读