简体   繁体   中英

Configure Nginx for React and Flask with Docker-Compose

I am trying to configure multiple Docker containers for a website with Nginx.

I have docker-compose working to spin up each container but I'm having trouble getting the React app to hit the Gunicorn WSGI server for the Flask API's when using Nginx.

Any idea why this might happen? It works fine without Nginx in the picture. Do I need an Nginx conf for the flask app also? Or is it a case of routing requests to the Gunicorn WSGI server from Nginx?

React frontend (container)

# 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'

Yes, you need to proxy the traffic in Nginx to the WSGI app, something like

server {
    listen 80;
    server_name your_domain www.your_domain;

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

read more here

Update

In this particular case, you will need to proxy to Gunicorn which is in a separate container, visible under the name middleware .

Because of that the uwsgi_pass directive should refer to that container:

server {
    listen 80;
    server_name your_domain www.your_domain;

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

Please mind, that if you're using Gunicorn -it recommends using proxy_pass , not uwsgi_pass .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM