在同一服务器用Nginx部署多Angular Docker容器遇资源加载问题
解决Angular容器静态资源404问题:Nginx代理配置修正方案
核心问题分析
访问https://example.net/example-backoffice时静态资源404,是因为:
- 主机Nginx的
/example-backoffice规则仅匹配单一路径,静态资源请求(如/main.xxx.js)会被转发到8000容器; - 容器内Nginx的路径映射规则错误,无法正确找到Angular打包后的静态资源。
修正方案(分两步)
1. 主机VM的Nginx配置调整
修改/example-backoffice的代理规则,确保所有前缀匹配的请求都转发到8001容器:
server { listen 443 ssl http2; server_name example.net; ssl_certificate /etc/nginx/ssl/cert_net_combined.crt; ssl_certificate_key /etc/nginx/ssl/example.net.key; location / { proxy_pass http://localhost:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # 修正后的backoffice代理规则 location /example-backoffice/ { proxy_pass http://localhost:8001/example-backoffice/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~ /myapi/api/(.*) { proxy_pass http://xxx.xxx.xx.x:8080/myapi/api/v1/$1$is_args$args; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass_request_headers on; } }
关键改动:
- 给
location和proxy_pass都加上末尾斜杠,确保https://example.net/example-backoffice/main.js会被转发到http://localhost:8001/example-backoffice/main.js - 避免匹配非预期路径(如
/example-backoffice-xxx)
2. 8001端口Angular容器的Nginx配置调整
修改路径映射规则,用alias替代默认的root匹配:
server { listen 8001; listen [::]:8001; server_name localhost; gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; # 修正后的静态资源匹配规则 location /example-backoffice/ { alias /usr/share/nginx/html/; index index.html; try_files $uri $uri/ /example-backoffice/index.html; } location / { port_in_redirect off; rewrite ^/$ /example-backoffice/ redirect; } error_page 404 /404.html; location = /404.html { internal; } error_page 500 502 503 504 /50x.html; location = /50x.html { internal; } proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; send_timeout 300; keepalive_timeout 300; }
关键改动:
- 使用
alias替代root,让/example-backoffice/main.js直接映射到容器内的/usr/share/nginx/html/main.js(Angular打包后的资源存放路径) - 调整
try_files的 fallback 路径,确保Angular路由刷新时能正确返回入口文件
3. 验证Angular打包配置
确保8001容器的Angular应用打包时正确指定baseHref:
ng build --base-href "/example-backoffice/"
该命令会生成正确的<base href="/example-backoffice/">,确保所有静态资源引用都带有前缀,避免请求根路径资源。
内容的提问来源于stack exchange,提问作者MiguelD
相关产品推荐
相关产品推荐

