'Proxy server nginx config - 502 bad gateway error

I have a fastapi as backend and an html file as a frontend which are supposed to be running on docker. Here are my file structure:

C:.
|   docker-compose.yaml
|
+---backend
|   |   api.py
|   |   Dockerfile
|   |   requirements.txt
|   |   __init__.py
|
\---frontend
        Dockerfile
        download.png
        index.html
        nginx.conf

frontend docker file:

FROM nginx:1.15
COPY . /usr/share/nginx/html
COPY ./nginx.conf /etc/nginx/conf.d/default.conf

backend docker file:

FROM python:3.9

COPY requirements.txt /app/

RUN pip install -r /app/requirements.txt

COPY ./ /app
CMD ["uvicorn", "app.api:app", "--host", "0.0.0.0", "--port", "8000"]

api.py:

app = FastAPI()

@app.post("/extract_text") 
async def create_upload_file(upload_file: UploadFile = File(...)):
    return FileResponse(path="Outputs/ocr_output.zip", filename="{}".format(allinall(upload_file))+"_output.zip", media_type='application/zip')

nginx.conf:

server {
  listen 80;

  location /extract_text {

      proxy_pass http://web;

  }
  
  location / {
    root /usr/share/nginx/html;
    index index.html index.html;
    try_files $uri $uri/ /index.html =404;
  }
  
  include /etc/nginx/extra-conf.d/*.conf;
}

docker compose:

version: "3.7"

services:

    
    web:
        build: frontend
        ports:
          - 80:80
        depends_on:
          - api

    api:
        build: backend

        ports:
          - 8000:80

Here is the error I receive:

"POST /extract_text HTTP/1.0" 502 560 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36" "-"

Don't know what's wrong with this while I addressed post command in nginx.conf file.



Solution 1:[1]

The issue was in nginx.config. it works well will the following config:

upstream api {
      server api:8000;
    }

    server {
        listen 80;
        charset utf-8;
        server_name  localhost;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/extra-conf.d/*.conf;

        gzip on;
        gzip_types text/css text/javascript application/x-javascript application/json;

        # backend urls
        location /extract_text {
            proxy_redirect off;
            proxy_pass http://api;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
        }

        # static files
        location /static {
            proxy_pass http://api;
        }

        # frontend
        location / {
            try_files $uri $uri/ /index.html;
        }
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CFD