Serving a dockerized react and django static files with nginx as web server and reverse proxy

I have simple dockerized react and django app that I'd like to serve using nginx as web server for serving both react and django's static files and as reverse proxy to forward user requests to the django backend served by gunicorn. But I have been struggling with nginx for serving react and django static files.

here is the nginx Dockerfile:

FROM node:18.16-alpine as build

WORKDIR /app/frontend/

COPY ../frontend/package*.json  ./

COPY ../frontend ./

RUN npm install

RUN npm run build


# production environment
FROM nginx

COPY  ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/frontend/build /usr/share/nginx/html

here is the docker-compose file:

version: '3.9'

services:
  db:
    image: mysql:8.0
    ports:
      - '3307:3306'
    restart: unless-stopped
    env_file:
      - ./backend/.env
    volumes:
      - mysql-data:/var/lib/mysql
  backend:
    image: vinmartech-backend:latest 
    restart: always
    build: 
      context: ./backend
      dockerfile: ./Dockerfile  
    ports:
      - "8000:8000"
    volumes:
      - static:/app/backend/static/

    env_file:
      - ./backend/.env
    depends_on:
      - db
  
  nginx:
    build:
      context: .
      dockerfile: ./nginx/Dockerfile
    ports:
      - "80:80"
    volumes:
      -  static:/app/backend/static/
    restart: always
    depends_on:
      - backend
      # - frontend

volumes:
  mysql-data: 
  static:

here is the nginx configuration file:


upstream mybackend {
    server backend:8000;
}

server {
    listen 80;

    location /letter/s {
        proxy_pass http://backend;
    }  

    location /contact/ {
        proxy_pass http://backend;
    }  


    location /admin/ {
        alias /static/;
    }      

    location /static/ {
        alias /static/;
    }

    location / {
      root /usr/share/nginx/html;
      try_files $uri $uri/ /index.html;
    }

}

here is the django settings for static file configuration:

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

It has been almost 4 months trying to find a solution but I'm still stuck. Can someone please come to my rescue? Please guy take a close look a this and help out.

Back to Top