在使用 Docker 部署前端服务时,我将 Nginx 配置为反向代理,用于将前端请求转发到后端服务。前端服务通过 Nginx 部署在 Docker 容器中,而后端服务则运行在宿主机上。Nginx 配置了代理,将请求转发到 localhost:8080
,即宿主机上由 IDEA 运行的后端 Web 服务。然而,前端请求未能正确到达后端,导致反向代理失败。
然后会出现 502
网关错误 POST http://localhost/api/employee/login 502 (Bad Gateway)
2024/08/21 00:42:39 [error] 20#20: *40 connect() failed (111: Connection refused) while connecting to upstream, client: 192.168.65.1, server: localhost,
request: "POST /api/employee/login HTTP/1.1", upstream: "http://127.0.0.1:8080/admin/employee/login",
host: "localhost", referrer: "http://localhost/"
2024/08/21 00:42:40 [error] 20#20: *40 no live upstreams while connecting to upstream, client: 192.168.65.1, server: localhost,
request: "POST /api/employee/login HTTP/1.1", upstream: "http://localhost/admin/employee/login", host: "localhost", referrer: "http://localhost/"
2024/08/21 00:42:40 [error] 20#20: *40 no live upstreams while connecting to upstream, client: 192.168.65.1, server: localhost,
request: "POST /api/employee/login HTTP/1.1", upstream: "http://localhost/admin/employee/login", host: "localhost", referrer: "http://localhost/"
要让容器中的 Nginx 能够正确访问宿主机上的服务,有以下两种解决方案:
host.docker.internal
location /api/ {
proxy_pass http://host.docker.internal:8080/admin/;
}
这种方式使得 Nginx 可以通过 host.docker.internal
直接访问宿主机上的服务。
location /api/ {
proxy_pass http://<宿主机IP地址>:8080/admin/;
}
在容器化应用程序中,特别是涉及到 Nginx 反向代理时,需要明确区分容器内部网络与宿主机网络之间的关系。通过调整 Nginx 配置,可以确保前端请求正确转发到宿主机上的后端服务,解决代理失败的问题。