Home > Blockchain >  How to configure Nginx reverse proxy properly?
How to configure Nginx reverse proxy properly?

Time:01-17

I have one create-react-app application, containerized with below Dockerfile.

FROM node:10-alpine as build
WORKDIR /app
COPY package.json .
RUN npm install --production
COPY . .
RUN npm run build

FROM nginx:1.21.5-alpine
RUN rm -rf /etc/nginx/conf.d
COPY conf /etc/nginx
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

The conf.d for Nginx

upstream api {
  server api:5000;
}

server {
  listen 80;

  location / {
    root /usr/share/nginx/html;
  }
}

server {
  listen 5000;

  location / {
    proxy_pass http://api;
  }

}

I have one expressjs application, containerized with below Dockerfile.

FROM node:10-alpine
WORKDIR /app
COPY package.json /app
RUN npm install --production
COPY . /app
CMD node index.js
EXPOSE 5000

I build docker image for each app so I have to docker image:

  1. NginxImage (ReactJS Application)
  2. NodeJsImage

I try to run both of the image using docker with below docker-compose:

version: "3.4"
services:
  app:
    image: NginxImage
    hostname: app
    ports:
      - "3001:80"
    networks:
      - local_deploy
  api:
    image: NodeJsImage
    hostname: api
    ports:
      - "5001:5000"
    networks:
      - local_deploy
networks:
  local_deploy:
    driver: bridge

But when I try to open the reactjs application within browser, and when the reactjs app call http://api:5000 I got error ERR_NAME_NOT_RESOLVED

I try to access the api within container

docker exec -it app /bin/sh

and I can get the response from the api

# curl api:5000

Is my reverse-proxy is not properly configured?

CodePudding user response:

Thank you for the hint @David, @Beppe and @Yusuf. In my case I just change the API endpoint to the app address it self.

Example if the app run on

localhost:3001

Then I set the api endpoint to be

localhost:3001/api

In the nginx config I add another location in the server block with re-write condition

upstream api {
  server api:5000;
}

server {
  listen 80;

  location / {
    root /usr/share/nginx/html;
  }

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://api
  }
}
  •  Tags:  
  • Related