【问题标题】:Configure Nginx for React and Flask with Docker-Compose使用 Docker-Compose 为 React 和 Flask 配置 Nginx
【发布时间】:2020-04-30 21:20:14
【问题描述】:

我正在尝试使用 Nginx 为网站配置多个 Docker 容器。

我让 docker-compose 工作以启动每个容器,但在使用 Nginx 时,我无法让 React 应用程序访问 Gunicorn WSGI 服务器以获取 Flask API。

知道为什么会发生这种情况吗?图片中没有 Nginx 也能正常工作。我还需要烧瓶应用程序的 Nginx conf 吗?还是从 Nginx 将请求路由到 Gunicorn WSGI 服务器的情况?

React 前端(容器)

# build environment
FROM node:12.2.0-alpine as build
WORKDIR /usr/src/app
ENV PATH /usr/src/app/node_modules/.bin:$PATH
COPY package.json /usr/src/app/package.json
RUN npm install --silent
RUN npm install react-scripts@3.0.1 -g --silent
COPY . /usr/src/app
RUN npm run build

# production environment
FROM nginx:1.16.0-alpine
COPY --from=build /usr/src/app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Nginx.conf

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;
  }

}

Docker-compose

version: '3.7'

services:
  middleware:
  build: 
      context: ./middleware
      dockerfile: Dockerfile.prod
  command: gunicorn --bind 0.0.0.0:5000 main:app
  ports:
    - 5000:5000
  env_file:
    - ./.env.prod
frontend:
  container_name: frontend
  build:
    context: ./frontend/app
    dockerfile: Dockerfile.prod
  ports:
  - '80:80'

【问题讨论】:

  • 日志中是否有任何错误?
  • 对此并不满意,但仍在尝试

标签: reactjs docker nginx flask docker-compose


【解决方案1】:

是的,您需要将 Nginx 中的流量代理到 WSGI 应用程序,例如

server {
    listen 80;
    server_name your_domain www.your_domain;

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/sammy/myproject/myproject.sock;
    }
}

阅读更多here

更新

在这种特殊情况下,您需要代理 Gunicorn,它位于一个单独的容器中,在名称 middleware 下可见。

因为 uwsgi_pass 指令应该引用那个容器:

server {
    listen 80;
    server_name your_domain www.your_domain;

    location / {
        include uwsgi_params;
        uwsgi_pass http://middleware:5000;
    }
}

请注意,如果您使用 Gunicorn -it recommends 使用 proxy_pass,而不是 uwsgi_pass

【讨论】:

  • 您是否建议对位于前端容器中的 Nginx 配置进行这些更改?还是应该为 Nginx 创建一个单独的容器?
  • 查看您的构建 - 前端是您拥有 nginx 的地方,它应该公开 WSGI。所以应该放在里面。您需要调整以反映您的 WSGI 配置(例如路径)。
  • 不幸的是,这些配置更改用于不同的方法(每个链接) - 我正在使用 docker-compose 来编排所有内容,因此需要将连接路由到另一个容器,而不是本地 uWSGI 服务器
  • 编辑后的答案导致 Nginx 直接路由到 uWSGI/flask 容器,而不是将 API 请求从 React 路由到 Flask