容器化 ReactJs 应用程序(来自 nginx 映像)不提供所有路由

ch.*_*h.E 3 nginx docker reactjs dockerfile docker-compose

我正在尝试在 GKE 上部署 ReactJS 服务。我使用 Nginx 构建我的 React 镜像(我使用了 create-react-app 和 React router)。

这是我的 dockerfile

FROM node:8.9.3-alpine as build-deps2
RUN mkdir /irooltest WORKDIR /irooltest COPY . /irooltest
RUN npm install RUN npm run build

FROM nginx:1.12-alpine 
COPY --from=build-deps2 /irooltest/build /usr/share/nginx/html
EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]
Run Code Online (Sandbox Code Playgroud)

这是我的 docker compose 文件:

services:
  irooltest:
     image: chaimaennar/irooltest
     ports:
      - 8080:80
     networks:
            default:

networks:
   default:
      external:
        name: mynetwork
Run Code Online (Sandbox Code Playgroud)

我尝试将我的应用程序导出到 80 以外的端口,但我无法(我知道这是由于 nginx,我默认配置为在端口 80 上提供服务)。

另一个问题是,运行我的应用程序时,它只显示根页面,任何其他(我用反应路由器定义的路由)显示:

404 未找到 nginx/1.12.2

当我看到源代码(在浏览器的检查部分)时,我看到:

-Top
  -localhost:8080
    -static
    -index.css
  -Webpack://
Run Code Online (Sandbox Code Playgroud)

在 webpack 下我可以看到我的所有文件夹(代码)。

这些是我的路线:

  <Route path="/home" render={(props) => <Layout auth={auth} {...props} />} /> 
  <Route path="/" render={(props) => <App auth={auth} {...props} />} /> 
  <Route path="/logo" render={(props) => <Logo />} /> 

  <Route path="/callback" render={(props) => {
    handleAuthentication(props);
    return <Callback {...props} /> }}/>

  <Route path="/profile" render={(props) => (<Profile auth={auth} {...props}/>
    )
} /> 

<Route path="/user" render={(props) => <UserForm auth={auth} {...props} />} />
</div>
</Router>
Run Code Online (Sandbox Code Playgroud)

我的问题是:

这是正常行为吗?

nginx 是否应该进行特殊配置来提供路由服务?

ch.*_*h.E 5

事实证明,使用react-routerandnginx需要进行特定配置,因为它nginx无法真正识别我在应用程序代码中使用 React Router 指定的路由。

1. 将这些行添加到Dockerfile告诉 docker 不要使用conf.d默认nginx配置。

RUN rm -rf /etc/nginx/conf.d
COPY conf /etc/nginx
Run Code Online (Sandbox Code Playgroud)

2. 添加文件夹confconf.d文件default.conf

 conf
   |
    conf.d
    default.conf
Run Code Online (Sandbox Code Playgroud)

default.conf3. 在文件中添加这些行

server {
 listen 80;
  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
    root   /usr/share/nginx/html;
  }
}
Run Code Online (Sandbox Code Playgroud)

他们告诉 nginx 来提供index.html文件