【发布时间】:2023-04-09 19:00:01
【问题描述】:
我尝试通过 docker-compose 启动一些服务。其中之一是 nginx 反向代理,处理不同的路径。一条路径(“/react”)是到端口 80 上带有 nginx 的 containerized react_app。只有反向代理才能正常工作。另外,如果我在端口 80 上为 react_app 的 nginx 服务,一切正常。将两者结合而不更改配置中的任何内容都会导致 css 和 js 等静态文件出现 404。
设置 #1
更正路径 /test 到 Google。
docker-compose.yml
version: "3"
services:
#react_app:
# container_name: react_app
# image: react_image
# build: .
reverse-proxy:
image: nginx:latest
container_name: reverse-proxy
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
ports:
- '80:80'
nginx.conf(反向代理)
location /test {
proxy_pass http://www.google.com/;
}
设置 #2
没有反向代理。来自容器 react_app 内的 nginx 的正确答案。
docker-compose.yml
version: "3"
services:
react_app:
container_name: react_app
image: react_image
build: .
#reverse-proxy:
# image: nginx:latest
# container_name: reverse-proxy
# volumes:
# - ./nginx.conf:/etc/nginx/nginx.conf
# ports:
# - '80:80'
设置 #3(不起作用!)
使用 nginx 进行反向代理和 React App。加载 index.html,但失败,因此在 /static 中加载文件
nginx.conf(反向代理)
location /react {
proxy_pass http://react_app/;
}
docker-compose.yml
version: "3"
services:
react_app:
container_name: react_app
image: react_image
build: .
reverse-proxy:
image: nginx:latest
container_name: reverse-proxy
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
ports:
- '80:80'
激活这两个系统会导致静态内容失败。在我看来,反向代理尝试为文件提供服务,但失败了(有充分的理由),因为 reac_app 的 nginx 中没有日志条目。这是来自 reac_app nginx 的配置,也许我遗漏了一些东西。
nginx.conf(在 react_app 容器内)
events {}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
location / {
try_files $uri /index.html;
}
}
}
-->更新
这是一个相当不令人满意的解决方法 - 但它确实有效。虽然现在反应路由搞砸了。 我无法访问 /react/login
http {
server {
server_name services;
location /react {
proxy_pass http://react_app/;
}
location /static/css {
proxy_pass http://react_app/static/css;
add_header Content-Type text/css;
}
location /static/js {
proxy_pass http://react_app/statics/js;
add_header Content-Type application/x-javascript;
}
}
}
【问题讨论】:
-
你没有向反向代理提供任何关于它应该如何处理你对 React 应用程序的请求的信息。您所说的只是侦听端口 80 上的调用并解析对 index.html 的任何调用,这可能不存在。我希望你的 React 应用程序在 3000 端口上运行,对吧?
-
反向代理正在通过 proxy_pass react_app 使用内部域名。因此,react_app 的 nginx 服务于 80。我尝试在端口 3000 上运行它并在我的机器上使用 nginx(而不是在 docker 内),这显示了相同的行为。在 react_app 容器中的路径
/usr/share/nginx/html上确实存在 index.html -
对不起,错过了那部分,没有意识到设置 #3 使用了以前的东西。看看这个stackoverflow.com/questions/57642492/…,说不定能搞清楚。
-
大家好,我也有同样的问题。 @DeVolt 你解决了吗?
标签: docker nginx proxy docker-compose