score:2

Accepted answer

First you need to specify proxy pass directive for your api calls - I would propose to add /api in your fetch calls. Than provide upstream using the same name for your backend service as specified in docker-compose.yml. It is important that backend service proceed the web service in docker-compose.yml, otherwise you would get connection error in nginx like this nginx: [emerg] host not found in upstream "backend:8080" You can update your nginx.conf as follows:

upstream backend {
  server backend:8080;
}

server {
  listen 80;
  
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://backend;
  }
  
  include /etc/nginx/extra-conf.d/*.conf;
}

Or simply in your case provide a proxy pass to localhost as follows:

server {
   listen 80;
      
   location / {
     root /usr/share/nginx/html;
     index index.html index.htm;
     try_files $uri $uri/ /index.html =404;
   }
  
   location /api {
     rewrite /api/(.*) /$1 break;
     proxy_pass http://localhost:8080;
   }
      
   include /etc/nginx/extra-conf.d/*.conf;
}

score:0

Sample Docker file, Included the Production build in the docker file

FROM node:15.6.0-alpine3.10 as react-build

# install and cache app dependencies
COPY package.json package-lock.json ./
RUN npm install && mkdir /react-frontend && mv ./node_modules ./react-frontend

WORKDIR /app/client/

COPY . .

RUN npm run build



# ------------------------------------------------------
# Production Build
# ------------------------------------------------------
FROM nginx:1.16.0-alpine
COPY --from=builder /react-frontend/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;"]

To add nginx as a server to our app we need to create a nginx.conf in the project root folder. Below is the sample file

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;
  }

}

Related Query

More Query from same tag