gpt4 book ai didi

reactjs - 如何在Prod中使用Docker和Nginx运行React?

转载 作者:行者123 更新时间:2023-12-02 19:52:24 24 4
gpt4 key购买 nike

我正在尝试在Docker Prod envir中运行动态路由,但在控制台检查器/空白页面中却收到404。为了使页面正常工作,我没有注释几行,您将在下面看到。我在网上找到了几个资源,并按照他们的设置进行了精确设置,但是没有用,这里是one。在localhost:3000上运行仅适用于某些页面,但不适用于动态路由...

资料夹结构

root
|- nginx
| |- nginx.conf
|- src
| |- App.js
| |- index.js
|- dockerfile-prod
|- dockerfile-compose-prod.yml

App.js
<BroserRouter> # is basename={} required?
<Switch>
<Route exact path ='/' exact component={Home} /> # works
<Route exact path='/article/:slug' component={Article} /> #does not work
<Route exact path='/blog' component={Blog} /> # works
...

dockerfile-prod
FROM node:alpine as build
WORKDIR /app
COPY . /app
ENV PATH /app/node_modules/.bin:$PATH
RUN yarn
RUN yarn build
FROM nginx:alpine

# COPY --from=build /app/build /usr/share/nginx/html #### BREAKS COMPLETELY SO I UNCOMMENT, THUS THE NEXT LINE

COPY ./build /var/www

# RUN rm /etc/nginx/conf.d/default.conf ### BREAKS COMPLETELY SO I UNCOMMENT

COPY nginx/nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

docker-compose-prod.yml
version: "3.7"
services:
react-prod:
container_name: react-prod
build:
context: .
dockerfile:
dockerfile-prod
ports:
- "3000:80"

nginx.conf
worker_processes auto;

events {
# Sets the maximum number of simultaneous connections that can be opened by a worker process.
worker_connections 8000;
# Tells the worker to accept multiple connections at a time
multi_accept on;
}


http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

# Sets the path, format, and configuration for a buffered log write
log_format compression '$remote_addr - $remote_user [$time_local] '
'"$request" $status $upstream_addr '
'"$http_referer" "$http_user_agent"';

server {
# listen on port 80
listen 80;
# save logs here
access_log /var/log/nginx/access.log compression;

# --- I AM THINKING THIS IS THE ISSUE HERE
root /var/www;

index index.html index.htm;

location / {
# First attempt to serve request as file, then
# as directory, then fall back to redirecting to index.html
try_files $uri $uri/ /index.html;
}

# Media: images, icons, video, audio, HTC
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
expires 1M;
access_log off;
add_header Cache-Control "public";
}

# Javascript and CSS files
location ~* \.(?:css|js)$ {
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}

location ~ ^.+\..+$ {
try_files $uri =404;
}
}
}

最佳答案

我认为这个问题可能在这里:

location ~ ^.+\..+$ {
try_files $uri =404;
}

我不是nginx专家,但是在我看来,它喜欢检查特定请求的位置是否存在适当的文件,如果不存在,则返回404。
对于React应用程序来说,这将是一件坏事,因为它是一个spa,所有请求都应重定向到index.html(js和媒体文件除外)。
我会尝试将其注释掉并查看效果。
如果不起作用,请尝试将 =404放入 index.html
休息看起来不错。

关于reactjs - 如何在Prod中使用Docker和Nginx运行React?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59814189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com