"proxy": "http://localhost:5000" 在开发阶段工作得非常好,因为 webpack DevServer 自己处理代理。一旦你部署了你的 React 应用程序,它就会停止运行。在尝试让我的容器化 React 应用程序与容器化 API 对话时,我遇到了同样的问题。我使用 Nginx 作为 Web 服务器来为 React 应用程序提供服务。我按照guide 将 Nginx 与 Docker 容器集成。这就是 nginx.conf 最初的样子:
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;
}
}
但是在我在这里和那里做了一些调整之后,我想出了这个配置(我会稍微谈谈 api 代表什么):
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
resolver 127.0.0.11;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://api:8000;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
发生了什么变化?我为 API 端点添加了一个根位置,因为它们都有一个公共前缀 /api。 proxy_pass 属性允许我们将所有来自 /api 的请求代理到通过端口 8000 公开的后端。api 只是在 docker-compose.yaml 中定义的容器的名称。
作为参考,这是我的 React 应用的 Dockerfile:
# build environment
FROM node:15.2.1 as build
WORKDIR /app
COPY ./client ./
RUN yarn
RUN yarn build
# production environment
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY --from=build /app/nginx/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
还有最重要的文件(docker-compose.yaml):
version: "3.8"
services:
client:
build:
context: .
dockerfile: client/Dockerfile
container_name: $CLIENT_CONTAINER_NAME
restart: unless-stopped
env_file: .env
ports:
- "1337:80"
networks:
- my-network
links:
- api
api:
build:
context: .
dockerfile: server/Dockerfile
container_name: $API_CONTAINER_NAME
restart: unless-stopped
env_file: .env
ports:
- "8000:8000"
networks:
- my-network
links:
- mongo
mongo:
image: mongo
container_name: $DB_CONTAINER_NAME
restart: unless-stopped
env_file: .env
environment:
- MONGO_INITDB_ROOT_USERNAME=$MONGO_INITDB_ROOT_USERNAME
- MONGO_INITDB_ROOT_PASSWORD=$MONGO_INITDB_ROOT_PASSWORD
- DB_NAME=$DB_NAME
- MONGO_HOSTNAME=$MONGO_HOSTNAME
volumes:
- ~/data/db:/data/db
ports:
- 27017:27017
networks:
- my-network
networks:
my-network:
driver: bridge