【问题标题】:How to successfully reverse proxy react application with ngnix?如何使用 nginx 成功反向代理反应应用程序?
【发布时间】:2021-07-22 12:06:12
【问题描述】:

我有一个在端口 8181 上运行的无容器节点应用程序。我正在尝试将 Ngnix 反向代理添加到使用 Dockerfile 部署到 docker 容器中的反应前端应用程序。我没有使用 docker-compose,但如果需要启动并运行它,我愿意。计划是让它在本地工作,并能够将其部署到谷歌的应用引擎 (F/E) 和谷歌云运行 (b/e),同时只需使用环境变量更新 proxy_pass 值。在本地,它以 502 bad gateway 的状态失败,我很难理解原因。有什么见解吗?希望每个请求都能从 localhost/api/* proxy_pass 到 localhost:8181/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/ngnix.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;
        }
    }
}

app-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

【问题讨论】:

    标签: node.js docker nginx docker-compose nginx-reverse-proxy


    【解决方案1】:

    我认为你使用暴露命令是错误的。据我所知,它没有得到第二个参数,只有第一个参数让用户知道他应该发布哪个端口。它仅供参考,它实际上并不发布端口。所以不妨试试

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

    【讨论】:

    • 这不起作用。 -p 80:80 将来自容器的所有请求映射到主机上的端口。它实际上阻止了应用程序的提供。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2016-01-12
    • 2019-08-09
    • 2021-02-04
    相关资源
    最近更新 更多