DeV*_*olt 4 proxy nginx docker docker-compose
我尝试通过 docker-compose 启动一些服务。其中之一是nginx 反向代理,处理不同的路径。一种路径(“/react”)是到一个容器化的react_app,在端口80上有一个nginx。唯一的,反向代理工作正常。另外,如果我在端口 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'
Run Code Online (Sandbox Code Playgroud)
nginx.conf(反向代理)
location /test {
proxy_pass http://www.google.com/;
}
Run Code Online (Sandbox Code Playgroud)
设置 #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'
Run Code Online (Sandbox Code Playgroud)
设置#3(不起作用!)
反向代理和使用 nginx 的 React App。加载index.html,但失败,因此加载/static中的文件
nginx.conf(反向代理)
location /react {
proxy_pass http://react_app/;
}
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)
激活这两个系统会导致静态内容失败。在我看来,反向代理尝试服务器文件,但失败了(有充分的理由),因为 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
--> 更新
这是一个相当令人不满意的解决方法——但它确实有效。虽然现在反应路由很混乱。我无法访问 /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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您在浏览器中检查丢失的静态文件的路径,您会发现它们的相对路径不是您所期望的。您可以通过在 nginx 反向代理配置中添加子过滤器来解决此问题。
http {
server {
server_name services;
location /react {
proxy_pass http://react_app/;
######## Add the following ##########
sub_filter 'action="/' 'action="/react/';
sub_filter 'href="/' 'href="/react/';
sub_filter 'src="/' 'src="/react/';
sub_filter_once off;
#####################################
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将更新静态文件的相对路径。
| 归档时间: |
|
| 查看次数: |
6452 次 |
| 最近记录: |