Backend Development 7 min read

Zero‑Downtime SpringBoot Port Sharing: Running Two Instances on the Same Port

This article explains how to achieve seamless code updates for SpringBoot applications by allowing two instances to share the same port, detailing the underlying Tomcat embedding mechanism, DispatcherServlet handling, and providing a complete Java implementation with step‑by‑step instructions and test results.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Zero‑Downtime SpringBoot Port Sharing: Running Two Instances on the Same Port

When updating code on a server, the usual approach is to stop the existing process before starting a new one, which causes temporary service interruption because the new process cannot bind to the same port. The article introduces a "black‑tech" method that enables two SpringBoot processes to truly share a single port, eliminating downtime.

The proposed solution involves checking if the default port is occupied, launching the new instance on an alternative port, and once the new instance is ready, swapping the ports and stopping the old process. This is achieved by leveraging Tomcat's embedded servlet container, the DispatcherServlet , and the ServletContainerInitializer mechanism.

Key technical points covered:

Understanding how SpringBoot embeds a servlet container (e.g., Tomcat) and how DispatcherServlet is registered.

Using TomcatServletWebServerFactory to obtain a ServletWebServerFactory and start/stop the web server programmatically.

Retrieving the collection of ServletContextInitializer beans via ServletContextInitializerBeans to ensure proper initialization.

Implementing a port‑checking utility ( isPortInUse ) and dynamically adjusting the server port.

The article provides a full Java implementation:

public class Main {
    public static void main(String[] args) {
        try {
            Tomcat tomcat = new Tomcat();
            tomcat.getConnector();
            tomcat.getHost();
            Context context = tomcat.addContext("/", null);
            tomcat.addServlet("/", "index", new HttpServlet(){
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    resp.getWriter().append("hello");
                }
            });
            context.addServletMappingDecoded("/", "index");
            tomcat.init();
            tomcat.start();
        } catch (Exception e) {}
    }
}

The core hot‑swap logic resides in WebMainApplication , which checks the default port (8088), starts a temporary instance on port 9090 if needed, then uses reflection to obtain the original ServletWebServerFactory , reconfigures it to the original port, starts the new server, and finally stops the old one.

@SpringBootApplication()
@EnableScheduling
public class WebMainApplication {
    public static void main(String[] args) {
        // ... port detection and argument adjustment ...
        ConfigurableApplicationContext run = SpringApplication.run(WebMainApplication.class, newArgs);
        if (needChangePort) {
            // kill old process, re‑configure Tomcat, start new server, stop old server
        }
    }
    // helper methods: invokeSelfInitialize, isPortInUse, getServletContextInitializerBeans, getWebServerFactory
}

A simple test controller ( TestPortController ) demonstrates that after deploying version 1, version 2 can be started without stopping the first instance; the service experiences at most a sub‑second interruption, confirming the zero‑downtime claim.

Overall, the article offers a practical, code‑first guide for backend developers to achieve seamless SpringBoot updates by sharing a single port between two running processes.

backendJavaSpringBootTomcatzero downtimePort Sharing
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.