首页 > 解决方案 > 如何在 Docker 中配置 NGINX 以使用在 localhost 上运行的 Spring Boot 应用程序?

问题描述

我尝试在 Docker 容器中使用 NGINX,同时我的 Spring Boot 应用程序在本地主机上运行(稍后在服务器上)。

NGINX 应该充当在端口 5500 上运行的应用程序的反向代理。该应用程序有一个用于 GET localhost:5500/test 的工作端点

@RestController
public class TestController {
    @GetMapping(value = "/test")
    public String get(){
        return "test";
    }
}

通过使用 NGINX,我尝试通过 localhost:8080/api/test 访问端点,但我总是得到一个 502 Bad Gateway。

Docker 容器内的 NGINX 配置

worker_processes 1;
events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
            location / {
            root /usr/share/nginx/html;
            try_files $uri /index.html;
        }

         location /api {
            proxy_pass http://127.0.0.1:5500/test;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-NginX-Proxy true;
            proxy_ssl_session_reuse off;
            proxy_set_header Host $http_host;
            proxy_cache_bypass $http_upgrade;
            proxy_redirect off;
        }
    }
}

NGINX 在/默认 index.html 上运行良好

NGINX 错误

[error] 31#31: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.22.0.1, server: , request: "GET /api/test HTTP/1.1", upstream: "http://127.0.0.1:5500/api/test", host: "127.0.0.1:8080"

"GET /api/test HTTP/1.1" 502 157 "-" "PostmanRuntime/7.28.1"

标签: spring-bootdockernginxdocker-composebad-gateway

解决方案


推荐阅读