unable to deploying react app under subdirectory on nginx running in docker container

Viewed 2402

I am unable to deploy my react app under a sub directory on nginx running in docker container.

Below are the details

  1. React app basename setting BrowserRouter basename='/myreactapp'
  2. Package.json has "homepage": "/myreactapp"
  3. nginx.conf

    server {
    
        server_name localhost;
    
        index index.html;
    
        error_log  /var/log/nginx/error.log;
    
        access_log /var/log/nginx/access.log;
    
        root /usr/share/nginx/html;
    
        location /myreactapp {
    
            try_files $uri $uri/ /myreactapp/index.html;
    
        }
    
    }
    
  4. Docker file

    FROM nginx:1.14.1
    COPY /build /usr/share/nginx/html
    COPY nginx.conf /etc/nginx/conf.d/default.conf
    EXPOSE 80
    CMD ["nginx", "-g", "daemon off;"]
    
  5. With this it still servers the app from '/' root location but not /myreactapp

2 Answers

In your Dockerfile, replace this line:

COPY /build /usr/share/nginx/html

with this:

COPY /build /usr/share/nginx/html/myreactapp

For me worked following this two articles

https://medium.com/@svinkle/how-to-deploy-a-react-app-to-a-subdirectory-f694d46427c1

https://medium.com/@darshanpawar/nginx-configuration-changes-after-you-deploy-react-application-in-a-sub-directory-f5b36453fed1

My nginx.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /myreactapp {
        try_files $uri $uri/ /myreactapp/index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

My Dockerfile

# replace nginx.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf
# copy files from build stage
COPY --from=build-stage /app/build /usr/share/nginx/html/myreactappenter
Related