knirb
knirb

Reputation: 143

Nginx config for multiple react apps (docker-compose)

For development, I'm trying to run two react apps, locally, on the same port (so both can share localStorage), where app1 runs on localhost:8000 and app2 runs on localhost:8000/app2. However, with the setup below I have the issue that all requests to localhost:8000/app2/... are routed to app1.

Is there a way around this?

nginx.conf

Update: moved /app2 block in front of / (see comment).

server {
  listen 8000;
  server_name localhost;

  location /app2 {
    proxy_set_header   X-Forwarded-For $remote_addr;
    proxy_set_header   Host $http_host;
    proxy_pass http://app2:3001;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
  }

  location / {
    proxy_set_header   X-Forwarded-For $remote_addr;
    proxy_set_header   Host $http_host;
    proxy_pass http://app1:3000; 
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
  }
}

docker-compose.yml

version: "3"
services: 
  nginx:
    image: nginx:latest
    ports:
      - "8000:8000"
    volumes: 
      - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
  app1:
    container_name: "app1"
    image: node:12
    ports:
      - "3000:3000"
    build:
      context: "./app1"
    volumes:
      - "./app1:/src/app"
  app2:
    container_name: "app2"
    image: node:12
    ports:
      - "3001:3001"
    build:
      context: "./app2"
    volumes:
      - "./app2:/src/app"

Dockerfile app1

And the app2 Dockerfile has EXPOSE 3001 and npm start --port 3001

FROM node:12    
WORKDIR /src/app    
COPY package*.json ./    
RUN npm install    
EXPOSE 3000    
CMD ["npm", "start", "--port", "3000"]

Upvotes: 1

Views: 2280

Answers (1)

knirb
knirb

Reputation: 143

I'll update this old question with an answer: The problem was not related to nginx or docker-compose. Instead, I was running two create-react-app applications in development mode and I forgot to set { "homepage": "/app2" } in package.json or set PUBLIC_URL=/app2 as environment variable to serve the app from a subdirectory.

Upvotes: 2

Related Questions