Search code examples
reactjsdockernginxhttp-status-code-404

how to fix 404 not found error nginx on docker?


I'm trying to make docker file run in to react app.react app all ready successfully deploy but page reload get an error 404 nginx error.

this is my docker file

FROM nginx:1.19.4-alpine
RUN rm -rf /usr/share/nginx/html/*
COPY build-qa /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Solution

  • Could be React Router DOM issue with nginx. Might check if you have the nginx.conf (local)

    # nginx.conf
    user  nginx;
    worker_processes  auto;
    error_log  /var/log/nginx/error.log warn;
    pid        /var/run/nginx.pid;
    events {
      worker_connections  1024;
    }
    http {
      include       /etc/nginx/mime.types;
      default_type  application/octet-stream;
      log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
      '$status $body_bytes_sent "$http_referer" '
      '"$http_user_agent" "$http_x_forwarded_for"';
      access_log  /var/log/nginx/access.log  main;
      sendfile        on;
      #tcp_nopush     on;
      
      keepalive_timeout  65;
      #gzip  on;
      #include /etc/nginx/conf.d/*.conf;
    server {
      listen 80;
      location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
      }
    }
    }
    

    Then try build the image and run. Sample Dockerfile content:

    FROM nginx
    # FROM node:8 as react-build
    
    WORKDIR /usr/share/react
    
    RUN curl -fsSL https://deb.nodesource.com/setup_17.x | bash -
    RUN apt-get install -y nodejs
    
    COPY package*.json ./
    RUN npm install
    
    COPY . .
    
    RUN npm run build
    
    RUN rm -r /usr/share/nginx/html/*
    
    RUN cp -a build/. /usr/share/nginx/html
    COPY nginx.conf /etc/nginx/nginx.conf
    
    # Build Image
    # docker build . -t <your-app-tag>:latest
    # Run Container
    # docker run -it --rm -d -p 8080:80/tcp --name <your-app-name> <your-app-tag>