如何用ngnix成功地反向代理react应用



我有一个在端口8181上运行的无容器节点应用程序。我正试图将Ngnix反向代理添加到react前端应用程序中,该应用程序通过使用Dockerfile部署到docker容器中。我不使用docker compose,但如果需要的话,我愿意使用它来启动和运行它。我们的计划是让它在本地工作,并能够将其部署到谷歌的应用程序引擎(F/E(和谷歌云运行(b/E(,同时简单地用环境变量更新proxy_pass值。在本地,它失败了,状态为502坏网关,我很难理解为什么。有什么见解吗?希望将每个请求从localhost/api/*proxy_pass传递到localhost:881/api/*。

我的后端路线:

/app.js

app.use('/api', require('./routes/index'));
app.use('/api/test', require('./routes/test.routes'));

/routes/index.js

router.get('/', function(req, res, next) {
  res.send('loading the app');
});

正在端口8181上运行。

前端:

app-web/nnix.conf

worker_processes 4;
events { worker_connections 1024; }
http {
    server {
        listen 80;
        root  /usr/share/nginx/html;
        include /etc/nginx/mime.types;
        location /api {
            resolver 127.0.0.11;
            proxy_pass http://127.0.0.1:8181$request_uri;
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

应用程序web/Dockerfile

# stage1 as builder
FROM node:10-alpine as builder
# copy the package.json to install dependencies
COPY package.json package-lock.json ./
# Install the dependencies and make the folder
RUN npm install && mkdir /app-web && mv ./node_modules ./app-web
WORKDIR /app-web
COPY . .
# Build the project and copy the files
RUN npm run build

FROM nginx:alpine
#!/bin/sh
COPY ./nginx.conf /etc/nginx/nginx.conf
## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*
# Copy from the stahg 1
COPY --from=builder /app-web/build /usr/share/nginx/html
EXPOSE 8181 80
ENTRYPOINT ["nginx", "-g", "daemon off;"]

接收错误的请求端点:

HTTP://localhost/api/

要在生成步骤之后运行的命令。

docker run -d --name app-web -p 80:80  app-web

我认为u r使用expose命令是错误的。据我所知,它没有得到第二个参数,只有第一个参数,它让用户知道他应该发布哪个端口。这只是为了提供信息,它实际上并没有发布端口。所以也许可以尝试

docker run -d --name app-web -p 8180:80 app-web

最新更新