Port Already in Use Spring Boot - Fixed

In Spring Boot applications, if you see an error indicating that a port is already in use, it means another process (possibly another instance of your application or a different application) is already running and using the desired port. Here's a typical error message:

***************************
APPLICATION FAILED TO START
***************************

Description:
Web server failed to start. Port 8080 was already in use.

Action:
Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

The default port for a Spring Boot web application is 8080

How to Resolve the "Port Already in Use" Error

Change the Spring Boot Application Port

You can change the port your Spring Boot application runs on by adding or modifying the server.port property in the application.properties or application.yml file:

server.port=8081

Or, if you're using YAML format:

server:
  port: 8081

Specify the Port Using Command Line

When running your Spring Boot application, you can specify the port directly using a command line argument:

java -jar your-app.jar --server.port=8081

Identify the Process Using the Port

You can identify the process using a specific port with various tools based on your operating system.

For Linux/macOS:

lsof -i :8080

For Windows:

netstat -ano | findstr 8080

Once identified, you can decide whether to kill the process or let it run.

Kill the Process

If you decide to kill the process of occupying the port.

For Linux/macOS:

kill -9 <PID>

Where <PID> is the process ID. 

For Windows:

taskkill /F /PID <PID>

This will free up the port, allowing you to start your Spring Boot application on it.

Ensure You're Not Starting the Application Multiple Times

If you're developing in an IDE, ensure you don't have multiple instances of your application running. This is a common oversight where developers might accidentally run the application more than once.

Use Random Port During Development

If you're not particular about the port and just want to run the application during development, you can configure Spring Boot to use a random port:

server.port=0

This will pick an available port from the system's available range. 

Remember, the root cause of the "port already in use" error is always another process that's already bound to the specified port. Whether you decide to change your application's port or stop the conflicting process depends on your specific needs and environment.

Comments