Yes, there is a Spring way of doing this:

Step 1. Adding an additional Tomcat connector

To add a port to the embedded server an additional connector needs to be configured. We will do it by providing custom WebServerFactoryCustomizer:

@Component
public class TomcatContainerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${swagger.port}")
    private int swaggerPort;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {

        Connector swaggerConnector = new Connector();
        swaggerConnector.setPort(swaggerPort);
        factory.addAdditionalTomcatConnectors(swaggerConnector);
    }
}

Now Tomcat listens on two ports but it serves the same content on both of them. We need to filter it.

Step 2. Adding a filter

Adding a servlet filter is pretty straightforward with a FilterRegistrationBean. It can be created anywhere, I added it directly to the TomcatContainerCustomizer.

@Component
public class TomcatContainerCustomizer  implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${swagger.port}")
    private int swaggerPort;

    @Value("${swagger.paths}")
    private List<String> swaggerPaths;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {

        Connector swaggerConnector = new Connector();
        swaggerConnector.setPort(swaggerPort);
        factory.addAdditionalTomcatConnectors(swaggerConnector);
    }

    @Bean
    public FilterRegistrationBean<SwaggerFilter> swaggerFilterRegistrationBean() {

        FilterRegistrationBean<SwaggerFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new SwaggerFilter());
        filterRegistrationBean.setOrder(-100);
        filterRegistrationBean.setName("SwaggerFilter");

        return filterRegistrationBean;
    }

    private class SwaggerFilter extends OncePerRequestFilter {

        private AntPathMatcher pathMatcher = new AntPathMatcher();

        @Override
        protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        FilterChain filterChain) throws ServletException, IOException {

            boolean isSwaggerPath = swaggerPaths.stream()
                    .anyMatch(path -> pathMatcher.match(path, httpServletRequest.getServletPath()));
            boolean isSwaggerPort = httpServletRequest.getLocalPort() == swaggerPort;

            if(isSwaggerPath == isSwaggerPort) {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } else {
                httpServletResponse.sendError(404);
            }
        }
    }
}

The properties swagger.port and swagger.paths are configured in the application.yaml:

server.port: 8080
swagger:
  port: 8088
  paths: |
    /swagger-ui.html,
    /webjars/springfox-swagger-ui/**/*,
    /swagger-resources,
    /swagger-resources/**/*,
    /v2/api-docs

So far so good: the swagger-ui is served on the port 8088, our api on the 8080. But there is a problem: when we try to connect to the api from the swagger-ui, the requests are sent to the 8088 instead of 8080.

Step 3. Adjusting SpringFox config.

Swagger assumes that the api runs on the same port as the swagger-ui. We need to explicitly specify the port:

@Value("${server.port}")
private int serverPort;

@Bean
public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
            .host("localhost:" + serverPort);
}

And the last problem: as the ui runs on a different port than the api, the requests are considered cross-origin. We need to unblock them. It can be done globally:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**/*").allowedOrigins("http://localhost:" + swaggerPort);
        }
    };
}

or by adding annotations to the controllers:

@CrossOrigin(origins = "http://localhost:${swagger.port}")

Versions used: SpringBoot 2.2.2.RELEASE, springfox-swagger2 2.9.2

For a working example see https://github.com/mafor/swagger-ui-port

Answer from Mafor on Stack Overflow
Top answer
1 of 2
6

Yes, there is a Spring way of doing this:

Step 1. Adding an additional Tomcat connector

To add a port to the embedded server an additional connector needs to be configured. We will do it by providing custom WebServerFactoryCustomizer:

@Component
public class TomcatContainerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${swagger.port}")
    private int swaggerPort;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {

        Connector swaggerConnector = new Connector();
        swaggerConnector.setPort(swaggerPort);
        factory.addAdditionalTomcatConnectors(swaggerConnector);
    }
}

Now Tomcat listens on two ports but it serves the same content on both of them. We need to filter it.

Step 2. Adding a filter

Adding a servlet filter is pretty straightforward with a FilterRegistrationBean. It can be created anywhere, I added it directly to the TomcatContainerCustomizer.

@Component
public class TomcatContainerCustomizer  implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${swagger.port}")
    private int swaggerPort;

    @Value("${swagger.paths}")
    private List<String> swaggerPaths;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {

        Connector swaggerConnector = new Connector();
        swaggerConnector.setPort(swaggerPort);
        factory.addAdditionalTomcatConnectors(swaggerConnector);
    }

    @Bean
    public FilterRegistrationBean<SwaggerFilter> swaggerFilterRegistrationBean() {

        FilterRegistrationBean<SwaggerFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new SwaggerFilter());
        filterRegistrationBean.setOrder(-100);
        filterRegistrationBean.setName("SwaggerFilter");

        return filterRegistrationBean;
    }

    private class SwaggerFilter extends OncePerRequestFilter {

        private AntPathMatcher pathMatcher = new AntPathMatcher();

        @Override
        protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        FilterChain filterChain) throws ServletException, IOException {

            boolean isSwaggerPath = swaggerPaths.stream()
                    .anyMatch(path -> pathMatcher.match(path, httpServletRequest.getServletPath()));
            boolean isSwaggerPort = httpServletRequest.getLocalPort() == swaggerPort;

            if(isSwaggerPath == isSwaggerPort) {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } else {
                httpServletResponse.sendError(404);
            }
        }
    }
}

The properties swagger.port and swagger.paths are configured in the application.yaml:

server.port: 8080
swagger:
  port: 8088
  paths: |
    /swagger-ui.html,
    /webjars/springfox-swagger-ui/**/*,
    /swagger-resources,
    /swagger-resources/**/*,
    /v2/api-docs

So far so good: the swagger-ui is served on the port 8088, our api on the 8080. But there is a problem: when we try to connect to the api from the swagger-ui, the requests are sent to the 8088 instead of 8080.

Step 3. Adjusting SpringFox config.

Swagger assumes that the api runs on the same port as the swagger-ui. We need to explicitly specify the port:

@Value("${server.port}")
private int serverPort;

@Bean
public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
            .host("localhost:" + serverPort);
}

And the last problem: as the ui runs on a different port than the api, the requests are considered cross-origin. We need to unblock them. It can be done globally:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**/*").allowedOrigins("http://localhost:" + swaggerPort);
        }
    };
}

or by adding annotations to the controllers:

@CrossOrigin(origins = "http://localhost:${swagger.port}")

Versions used: SpringBoot 2.2.2.RELEASE, springfox-swagger2 2.9.2

For a working example see https://github.com/mafor/swagger-ui-port

2 of 2
0

I don't think so. When you're setting the Spring Boot management port (management.server.port), a second application server gets started to serve the actuator stuff. As far as I know there is no possibility (apart from custom actuator endpoints) to publish something on that server.
What is your use case exactly? Do you want to prevent access to Swagger in production or for non-authenticated users?

🌐
GitHub
github.com › mafor › swagger-ui-port
GitHub - mafor/swagger-ui-port: Serving SpringFox' swagger-ui from a separate port.
Now Tomcat listens on two ports but it serves the same content on both of them. We need to filter it. Adding a servlet filter is pretty straightforward with a FilterRegistrationBean. It can be created anywhere, I added it directly to the TomcatContainerCustomizer. @Component public class TomcatContainerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> { @Value("${swagger.port}") private int swaggerPort; @Value("${swagger.paths}") private List<String> swaggerPaths; @Override public void customize(TomcatServletWebServerFactory factory) { Connector swaggerConnector =
Author   mafor
Discussions

spring boot - how to change <host:port> to domain in swagger - Stack Overflow
in the picture swagger request use host and port,so browser console XMLHttpRequest cannot load http://115.159.22.159:9001/bp/api/v1/user/1. No 'Access-Control-Allow-Origin' header is present on the More on stackoverflow.com
🌐 stackoverflow.com
April 20, 2017
How to set port?
There was an error while loading. Please reload this page · This is Springfox sample. https://staging.jakduk.com:8080/swagger-ui.html#!/게시판/getPostsUsingGET More on github.com
🌐 github.com
6
July 13, 2016
exposing swagger-ui on the management port
Is your feature request related to a problem? Please describe. My application is exposed on the server-port publicly, however, the management-port is not exposed publicly (actuator). I want to be a... More on github.com
🌐 github.com
3
November 3, 2020
Change Swagger request URL port - Flowable Application - Flowable
Hi all, I set up the flowable REST API at http://localhost:12080. Everytime I try to call an endpoint with swagger it tries to access http://localhost:8080 instead. E.g: How can I change the port that swagger tries to access? Kind regards 🙂 More on forum.flowable.org
🌐 forum.flowable.org
1
April 27, 2018
🌐
SpringDoc
springdoc.org › faq.html
F.A.Q
Since Spring Boot 2.2, this is the new property to handle reverse proxy headers: ... If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer interface. This might be necessary to remove the port number, for example.
🌐
Baeldung
baeldung.com › home › spring › spring boot › change swagger-ui url prefix
Change Swagger-UI URL prefix - Spring Boot
May 11, 2024 - Now let’s say we want to change this URL to http://localhost:8080/myproject/swagger-ui/index.html. Let’s review two approaches that can help us achieve it. Similar to the above example for SpringDoc, adding the following property in the application.properties file will help us change it successfully:
🌐
DEV Community
dev.to › raviyasas › enable-swagger2-with-spring-boot-4dp8
Enable Swagger2 with Spring Boot - DEV Community
June 8, 2021 - Now you are ready. Your REST controllers are now available on Swagger 2. You can access the Swagger documentation via http://localhost:8090/swagger-ui.html You may change the port with the port your application is running.
🌐
Medium
medium.com › @akshitaswami248 › swagger-configuration-in-spring-boot-application-8558492df54b
Swagger Configuration in Spring Boot Application | by Akshitaswami | Medium
July 10, 2023 - Swagger Configuration in Spring Boot Application Below are the steps to configure swagger in spring boot application. Step1: Add below dependencies in pom.xml …
Find elsewhere
🌐
Swagger
swagger.io › docs › open-source-tools › swagger-ui › usage › configuration
Configuration | Swagger Docs
PortalDeliver Up-to-date API Documentation · ExploreQuickly Test and Explore APIs · Functional TestingAutomated API Testing · Contract TestingBlock API Breaking ChangesSwagger Enterprise · Standardize your APIs with projects, style checks, and reusable domains.
🌐
GitHub
github.com › springfox › springfox › issues › 1387
How to set port? · Issue #1387 · springfox/springfox
July 13, 2016 - This is Springfox sample. https://staging.jakduk.com:8080/swagger-ui.html#!/게시판/getPostsUsingGET It used 8080 port. But, request URL not use 8080 port. https://staging.jakduk.com/api/board/free/posts?category=ALL ...
Author   Pyohwan
🌐
Baeldung
baeldung.com › home › rest › setting up swagger 2 with a spring rest api using springfox
Setting Up Swagger 2 with a Spring REST API | Baeldung
November 12, 2025 - To do so, we have to use the @EnableSwagger2 on our configuration class: @Configuration @EnableSwagger2 public class SpringFoxConfig { } Additionally, without Spring Boot, we don’t have the luxury of auto-configuration of our resource handlers.
🌐
GitHub
github.com › springdoc › springdoc-openapi › issues › 923
exposing swagger-ui on the management port · Issue #923 · springdoc/springdoc-openapi
November 3, 2020 - If it is set to true then expose the swagger ui using the management port.
Author   flamestro
🌐
Bell Software
bell-sw.com › blog › documenting-rest-api-with-swagger-in-spring-boot-3
How to use Swagger with Spring Boot
This step-by-step tutorial will guide you through integrating Swagger (based on OpenAPI 3.0 specification) into a Spring Boot project.
🌐
DevOn
devonblog.com › home › continuous delivery › swagger/openapi with spring boot
Swagger/OpenApi with Spring Boot - Devonblog
October 20, 2022 - Add it to the application.properties ...s/swagger-ui.html · Changing the title and other properties for swagger, Add the below annotation to the main class....
🌐
Google Groups
groups.google.com › g › swagger-swaggersocket › c › 9mSNi1fqKVU
Running Swagger-UI on different port
This launches a web server on port 8000, and swagger-ui is served up from http://localhost:8000/swagger-ui You can put in any URL to the UI (I've tested with port 8000, 8002, 8080) and there's no issue.
🌐
Javatpoint
javatpoint.com › spring-boot-change-port
Spring Boot Change Port
May 30, 2014 - SB Change Port - Spring Boot Change Port with Introduction, Features, Project, Starter Project Wizard, CLI, Application, Annotations, DM, Properties, Actuator, Thymeleaf View, JPA, JDBC etc
🌐
Medium
medium.com › @f.s.a.kuzman › using-swagger-3-in-spring-boot-3-c11a483ea6dc
Using Swagger 3 in Spring Boot 3. Apparently, Spring Boot 3 needs a… | by Fady Kuzman | Medium
April 23, 2025 - $ mvn spring-boot:run · Go to your browser and navigate to localhost:8080/swagger-ui.html · localhost and 8080 are the default for server name and port respectively. If you are running the application with different values, change them accordingly. Also, if you have a context path, which is usually set in your properties file you should add it.
🌐
Apidog
apidog.com › blog › swagger-ui-url
How to Change Swagger UI URL Defauth Path
February 5, 2026 - const express = require('express'); const app = express(); app.use('/custom-path', express.static('swagger-ui')); app.listen(3000, () => { console.log('Server is running on port 3000'); }); This will allow you to access your Swagger UI on your ‘custom-path’. In a Spring Boot application, you can modify ‘application.properties’ or ‘application.yml’ files.
🌐
Flowable
forum.flowable.org › flowable application
Change Swagger request URL port - Flowable Application - Flowable
April 27, 2018 - Hi all, I set up the flowable REST API at http://localhost:12080. Everytime I try to call an endpoint with swagger it tries to access http://localhost:8080 instead. E.g: [image] How can I change the port that swagger …
🌐
CodingNConcepts
codingnconcepts.com › spring-boot › how-to-configure-swagger
How to configure Swagger in spring boot - Coding N Concepts
September 4, 2020 - Instead of hard coding values in swagger configuration we are going to define properties in configuration file. We’re using application.yml to define properties. You may also use application.properties file. app: name: spring boot application api: title: Spring Boot APIs version: 1.0.0 description: Spring Boot APIs description base-package: com.abc.controller contact-name: apisupportgroup contact-email: apisupportgroup@abc.com swagger: enable: true
🌐
SpringDoc
springdoc.org
OpenAPI 3 Library for spring-boot
Since Spring Boot 2.2, this is the new property to handle reverse proxy headers: ... If you need to manually adjust the URL displayed in the Swagger UI, implement the ServerBaseUrlCustomizer interface.