Docker部署应用后Nginx反向代理路径无法访问的求助
反向代理Docker应用返回404问题排查与解决
问题背景
通过Docker容器部署了monitor.api和webapp两个服务,容器运行正常,但配置Nginx反向代理后,访问http://HOSTIP/monitorwebapp返回404,仅能通过http://HOSTIP:4206直接访问web应用,且Nginx错误日志无相关记录。
现有配置
docker-compose.yml
version: '3.4' services: monitor.api: image: ${DOCKER_REGISTRY-}monitorapi ports: - "5001:443" build: context: . dockerfile: monitor.API/Dockerfile webapp: image: ${DOCKER_REGISTRY-}monitorwebapp ports: - "4205:443" - "4206:80" build: context: ./monitor-webApp args: - BASE_API_URL=${BASE_API_URL} dockerfile: Dockerfile
Nginx配置
server { listen 80; server_name <HOST IP>; sendfile on; default_type application/octet-stream; gzip on; gzip_http_version 1.1; gzip_disable "MSIE [1-6]\."; gzip_min_length 256; gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript; gzip_comp_level 9; root /usr/share/nginx/html; location /monitorwebapp/ { proxy_pass http://<HOST IP>:4206/; 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_set_header X-Forwarded-Proto $scheme; } location /monitorapi/ { proxy_pass https://<HOST IP>:5001/api/; 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_set_header X-Forwarded-Proto $scheme; } }
解决步骤
1. 修正Nginx路径匹配规则
当前location /monitorwebapp/仅匹配带尾斜杠的请求,但用户访问的是无尾斜杠的/monitorwebapp,导致路径转发异常。可修改为同时匹配有无尾斜杠的规则:
location ~ ^/monitorwebapp(/.*)?$ { proxy_pass http://<HOST IP>:4206$1; 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_set_header X-Forwarded-Proto $scheme; }
或简化为不带尾斜杠的location配置:
location /monitorwebapp { proxy_pass http://<HOST IP>:4206/; 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_set_header X-Forwarded-Proto $scheme; }
2. 配置web应用的基础路径
web应用默认以根路径/部署,通过/monitorwebapp访问时,静态资源(JS、CSS等)的请求路径仍会以/开头,导致资源找不到。需在构建时指定基础路径:
- 若为Angular应用,在docker-compose的webapp构建参数中添加
BASE_HREF:
并在Dockerfile中使用该参数执行构建:build: context: ./monitor-webApp args: - BASE_API_URL=${BASE_API_URL} - BASE_HREF=/monitorwebapp/ dockerfile: DockerfileARG BASE_HREF RUN ng build --base-href ${BASE_HREF}
3. 开启Nginx访问日志排查
添加访问日志配置,查看实际转发的请求路径是否符合预期:
access_log /var/log/nginx/monitor_access.log;
通过日志分析请求转发细节,定位路径不匹配问题。
4. 验证容器内部路径映射
进入webapp容器,确认静态文件部署路径正确:
docker exec -it <webapp-container-id> ls /usr/share/nginx/html
确保容器根路径下存在index.html等核心文件。
5. 调整Host头配置(可选)
若webapp依赖Host头判断访问路径,可将proxy_set_header Host设置为容器的实际端口:
proxy_set_header Host <HOST IP>:4206;
内容的提问来源于stack exchange,提问作者maaajo
相关产品推荐
相关产品推荐

