Docker环境下Nginx反向代理Spring Boot后端遇连接拒绝问题求助
解决Nginx反向代理后端出现502 Bad Gateway的问题
根据你提供的日志和配置,核心问题是Nginx无法连接到后端Spring Boot网关容器(172.20.0.3:9093),以下是具体排查和解决步骤:
1. 验证后端服务是否正确监听容器内的9093端口
Spring Boot默认可能只绑定localhost,导致容器外部(包括Nginx)无法访问。
- 进入后端容器:
docker exec -it webplatform-b-applicationgateway-1 sh - 检查端口监听情况:
输出应显示服务绑定# 容器内无netstat时用ss命令 ss -tulpn | grep 90930.0.0.0:9093,而非127.0.0.1:9093。如果是后者,修改后端配置文件(application.properties/yaml):server.address=0.0.0.0 server.port=9093
2. 测试Nginx容器与后端的连通性
确认Nginx能通过容器别名访问后端服务:
- 进入Nginx容器:
docker exec -it webplatform-nginx-1 sh - 先ping后端别名,确认网络连通:
ping b-applicationgateway - 再测试端口连通性,直接调用后端接口:
如果这里也出现连接拒绝,说明问题出在后端服务本身或容器网络配置,而非Nginx。curl -v http://b-applicationgateway:9093/authenticate
3. 确保后端服务完全启动后Nginx才启动
depends_on仅保证容器启动,不保证服务就绪。后端Spring Boot启动需要时间,Nginx启动时可能后端还没准备好。
修改docker-compose.yaml,给后端添加健康检查:
b-applicationgateway: # 原有配置... healthcheck: test: ["CMD", "curl", "-f", "http://localhost:9093/actuator/health"] interval: 10s timeout: 5s retries: 5
同时修改Nginx的depends_on,等待后端健康:
nginx: # 原有配置... depends_on: - f-frontend b-applicationgateway: condition: service_healthy
注意:需要后端添加Spring Boot Actuator依赖并启用健康端点
4. 检查Nginx代理路径配置是否匹配后端接口
当前Nginx配置:
location /api/ { proxy_pass http://backend/; }
该配置会将/api/authenticate转发为http://backend/authenticate,请确认后端接口路径是/authenticate而非/api/authenticate。如果后端接口带/api前缀,修改proxy_pass去掉末尾的斜杠:
location /api/ { proxy_pass http://backend; }
5. 查看后端容器日志确认服务状态
检查后端服务是否真的启动成功:
docker logs webplatform-b-applicationgateway-1
寻找类似Started ApplicationGatewayApplication in X seconds的日志,确认服务启动正常,端口为9093。
内容的提问来源于stack exchange,提问作者Daniele00
相关产品推荐
相关产品推荐

