The problem
I am running a Java application using the Spring Framework, and I encountered the following error while running the application in Eclipse:
***************************
APPLICATION FAILED TO START
***************************
Description:
Web server failed to start. Port 8081 was already in use.
Action:
Identify and stop the process that's listening on port 8081 or configure this application to listen on another port.
Eclipse provided me with a recommendation to identify and close the application that is listening on port 8081. I figured out two ways to close a port. On is using the terminal and the other is using Eclipse.
Stop a process from listening on a port using the macOS terminal
If you are using macOS, then a solution is to identify and stop the process that is listening to port 8081 using the terminal.
Follow the steps to fix “Web server failed to start. Port 8081 was already in use.”
Step one: Open the terminal
Using your keyboard, press command + F
to launch the search bar. Type “terminal” and click on the terminal icon to launch the terminal.
Step two: Find the PID
Using the terminal, enter the following command to show a list of ports and their PID
sudo lsof -PiTCP -sTCP:LISTEN
Enter your password when prompted, and look for the port number you are trying to close. Take note of the PID associated with the port number. The PID for port 8081 on my machine is 2281.
Example
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 2281 myusername 54u IPv6 x9584b9da175da381 t TCP *:8081 (LISTEN)
Step three: Close the port
Once you have identified the PID for the required port, enter the following command to close the port.
sudo kill -9 2281
Replace 2281 with your PID, and enter your password when prompted.
You will not be given a confirmation that the port was closed. Go back to Eclipse and run your Java application as usual, and it should work now that port 8081 is available for use.
Alternatively, you can close the application using Eclipse and free the port.
Close a Java application using Eclipse and free the port
Instead of stopping the process that is using port 8081 (or the port that Eclipse is prompting you to close) using the terminal, you can just shut down the current Java application that is using the port in Eclipse.
If you run sudo lsof -PiTCP -sTCP:LISTEN
you will notice that Java is actually using port 8081.
Output
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 2281 myusername 54u IPv6 x9584b9da175da381 t TCP *:8081 (LISTEN)
To stop a process from listening to a port using Eclipse, click Remove Launch
and then click Terminate
. Both buttons are located above the Eclipse terminal.
Final thoughts
Before closing a port, you should make sure that it is not being used for something important. In my case, port 8081 was being used by Java, and I did not care about closing it to reuse it for another Java application.
Hope that helped!