Search code examples
javascriptspringspring-bootnginxswagger

Spring Boot Swagger through Nginx does not work correctly


I have configured two services running in separate containers through nginx. Nginx configuration:

server {
    listen 8080;

    location /template-order-service/ {
        proxy_pass_request_headers on;
        proxy_set_header Host $host;

        proxy_pass http://template-order-service:8082/;
    }

    location /template-product-service/ {
        proxy_pass_request_headers on;
        proxy_set_header Host $host;

        proxy_pass http://template-product-service:8083/;
    }

}

I am able to call both services as exptected, using:

http://localhost/template-order-service/<endpoint>
http://localhost/template-product-service/<endpoint>

However when I am trying to reach swagger i am getting

Failed to load remote configuration.

In debugger console I see error like this:

http://localhost/v3/api-docs/swagger-config 404 Not Found

I am sure that this url should be:

http://localhost/template-order-service/v3/api-docs/swagger-config

or

http://localhost/template-product-service/v3/api-docs/swagger-config

How can I fix that in swagger ? In .js file I see some configUrl variable but I don't know how to overwrite it. Simple query param (?configUrl=/template-order-service/v3/api-docs/swagger-config) does not work.


Solution

  • I think X-Forwarded- headers should help you.
    Namely X-Forwarded-Prefix to set context path for swagger-ui.

    Try this nginx config:

    server {
        listen 8080;
    
        location /template-order-service/ {
            proxy_pass_request_headers on;
            proxy_set_header Host $host;
            
            proxy_set_header X-Forwarded-Prefix '/template-order-service';
    
            proxy_pass http://template-order-service:8082/;
        }
    
        location /template-product-service/ {
            proxy_pass_request_headers on;
            proxy_set_header Host $host;
            
            proxy_set_header X-Forwarded-Prefix '/template-product-service';
    
            proxy_pass http://template-product-service:8083/;
        }
    
    }
    

    You might also need to set property for spring boot app: server.forward-headers-strategy=framework

    After that you should be able to open swagger-ui at http://localhost(or where your nginx is)/template-order-service/swagger-ui/index.html and http://localhost/template-product-service//swagger-ui/index.html

    You can check more documentation and other headers to modify URL here:
    https://springdoc.org/#how-can-i-deploy-springdoc-openapi-ui-behind-a-reverse-proxy