用于多个 React 应用程序的 Nginx 配置(docker-compose)

Nginx config for multiple react apps (docker-compose)

为了开发,我正在尝试 运行 两个 React 应用程序,在本地,在同一端口上(因此两者可以共享 localStorage),其中 app1 [= localhost:8000 上的 52=]s 和 localhost:8000/app2 上的 app2 运行s。但是,通过下面的设置,我遇到了所有对 localhost:8000/app2/... 的请求都被路由到 app1.

的问题

有办法解决这个问题吗?

nginx.conf

更新:将 /app2 块移动到 / 前面(见评论)。

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

并且 app2 Dockerfile 有 EXPOSE 3001npm start --port 3001

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

我将用答案更新这个老问题:该问题与 nginx 或 docker-compose 无关。相反,我是 运行 两个处于开发模式的 create-react-app 应用程序,我忘记在 package.json 中设置 { "homepage": "/app2" } 或设置 PUBLIC_URL=/app2 作为环境变量来为应用程序提供服务一个子目录。