Question
How can I manage the embedded instance of Apache Tomcat in my Spring Boot application?
// application.properties
server.port=8090
Answer
When developing a Spring Boot application, you might encounter issues with the embedded Apache Tomcat server, particularly when trying to change the port it's listening on. This can happen if the previous instance of the server is still running, or if there's an existing process utilizing that port. Below, we will explore how to configure your application properties and reliably manage your embedded Tomcat instance.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory servletContainer() {
return new TomcatServletWebServerFactory();
}
}
Causes
- The specified port (e.g., 8090) is already in use by another application or another instance of the same application.
- The application has not been properly stopped from a previous run, causing the port to remain busy.
- Incorrect configuration in the application.properties file may lead to connectivity issues.
Solutions
- Check for running processes on the specified port and stop those processes if necessary.
- Ensure that your application is completely stopped before restarting it, which can be done by properly shutting down the application from your IDE or terminal.
- Modify the application to check for the availability of the specified port before attempting to bind to it. This could involve wrapping the server startup in a try-catch block and handling exceptions appropriately.
Common Mistakes
Mistake: Not stopping the application from the IDE before a subsequent run.
Solution: Always ensure you stop the running application before attempting to restart it.
Mistake: Trying to bind to a port that is still being used by another service.
Solution: Use `netstat -ano | findstr :8090` (on Windows) or `lsof -i :8090` (on Mac/Linux) to find and stop the process occupying the port.
Helpers
- Spring Boot
- Embedded Tomcat
- Server Port Configuration
- Spring Framework
- REST API Development
- Tomcat Connector Error
- Port Already in Use
- Application Configuration