To configure Swagger in a Spring Boot microservices architecture using Eureka and an API Gateway, ensuring requests are routed through the API Gateway rather than internal Docker URLs, you can follow these steps:
Solution: Use springdoc.swagger-ui
Configuration
- Add
server.servlet.context-path
for Each Microservice
Ensure each microservice has a unique context path in itsapplication.properties
orapplication.yml
.
For example, in thecustomer-service
:
server.servlet.context-path=/customer
- Update Swagger Base Path with
springdoc
Custom Configuration
In each microservice, override the Swagger OpenAPI URL configuration to use the API Gateway’s base path. Add this configuration to theapplication.yml
orapplication.properties
:
springdoc.swagger-ui.path=/swagger-ui.html
springdoc.api-docs.path=/v3/api-docs
springdoc.api-docs.url=http://localhost:8081/{service-context}/v3/api-docs
- Set
eureka.instance.hostname
to Gateway Hostname
Ensure that Eureka registers each service with the Gateway hostname instead of the internal Docker hostname. In each microservice’sapplication.yml
, configure:
eureka:
instance:
hostname: localhost # Use API Gateway hostname
metadata-map:
instanceId: ${spring.application.name}:${server.port}
client:
service-url:
defaultZone: http://localhost:8761/eureka/
- Add Custom Gateway Route Configuration for Swagger
Configure the Gateway routes to expose each microservice’s Swagger documentation. In the API Gateway’sapplication.yml
:
spring:
cloud:
gateway:
routes:
- id: customer-service
uri: lb://customer-service
predicates:
- Path=/customer/**,/customer/v3/api-docs
- Expose Swagger Through Gateway URL
Access Swagger UI for each service via:
http://localhost:8081/customer/swagger-ui.html
- Requests to
/customer/V1
will route through the Gateway.
Alternative Solution: Use API Gateway for Aggregated API Documentation
- Enable Swagger Aggregation in API Gateway
Usespringdoc-openapi-gateway
dependency to aggregate documentation:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-gateway</artifactId>
<version>1.6.15</version>
</dependency>
- Configure API Gateway for Swagger Aggregation
Inapplication.yml
of the Gateway:
springdoc:
swagger-ui:
path: /swagger-ui.html
api-docs:
groups:
enabled: true
openapi:
paths-to-match: /v3/api-docs/**
- Access Aggregated Swagger UI
Access all microservices’ Swagger docs from a single location at:
http://localhost:8081/swagger-ui.html
Keywords
- “Spring Boot Swagger behind API Gateway”
- “Swagger API Gateway Docker microservices”
- “Spring Boot Swagger Eureka internal Docker URL fix”
- “Aggregate Swagger documentation Spring Cloud Gateway”
- “SpringDoc Swagger API Gateway routing issues”