Search code examples
dockernginxdocker-composecorsdevops

Configuring nginx on the server for requests from docker to docker-compose (CORS problem)


I have to deploy my application which consists of two parts to be deployed on the server, the frontend part packaged in dockerfile is deployed without problems, as is the backend part packaged in docker-compose, but there is a problem with requests as I think in the middle of docker-compose. I have a frontend part that is packaged in a dockerfile.

    #STAGE 1
FROM node:16-alpine as build
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm install --legacy-peer-deps
COPY . .
RUN npm run build --prod

#STAGE 2
FROM nginx:1.17.1-alpine
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /usr/src/app/dist/ok-admin /usr/share/nginx/html

Nginx:

events{}
http {
    include /etc/nginx/mime.types;
    server {
        listen 80;
        server_name ok-market.pp.ua;
        root /usr/share/nginx/html;
        index index.html;
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
}

and I have a backend part that is packaged in docker compose:

version: '3'
services:
  app:
    build:
      context: .
    ports:
      - "3000:3000"
    environment:
      - MONGODB_URI=mongodb://mongo:27017/market
    depends_on:
      - mongo
    networks:
      - backend
    command: ["sh", "-c", "sleep 10 && npm start"]

  mongo:
    image: mongo
    ports:
      - "27017:27017"
    networks:
      - backend

networks:
  backend:
    driver: bridge

index.ts:

const corsOptions = {
    origin: 'http://ok-market.pp.ua'
};

app.use(cors(corsOptions));

Everything works locally, but requests do not go through on the server enter image description here


Solution

  • Most likely, you are sending requests from the frontend to the backend via localhost:3000. However, the frontend operates in such a way that the code is executed on your local machine, and a request to localhost:3000 is directed to your local machine.

    Therefore, you need to specify the request from the frontend to the backend in this format: ipaddress:3000 or create a subdomain api.example.com and set up a reverse proxy for this (best way).

    About CORS you can fix it in your backend app. Or add headers in backend reverse proxy

    add_header Access-Control-Allow-Origin http://localhost;