Find and kill a process on a specific port (lsof)
You might all have experienced the situation when you want to start a server either from within your IDE or via the terminal to only get the error that the “port is already in use” and the startup is aborted. This is mostly caused by aborting the server or a crash of the IDE which started it and not terminating it properly. When using macOS (or any other BSD or a Linux) there is a simple solution for this.
For such purposes macOS comes with the “lsof” command which stands for “list open files”. Its purpose is to show who is using a specific file or in our case who is using a specific port. After identifying the process it is easy to terminate it using the “kill” command.
To use lsof for such a scenario you have to launch the terminal app first. When we take a tomcat server for example which is listening on port 8080 we have to type the following line to the terminal:
lsof -i:8080
The -i option awaits a ip address. As we don’t know the address we just give it the port number.
This returns a list of all processes currently listening to port 8080:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 30268 areyouready 50u IPv6 0x73c99f19aca91277 0t0 TCP *:http-alt (LISTEN)
There obviously should be only one process listening to that port which is a java process. As tomcat is a java application this seems to be what we have thought. To free the port now it is necessary to kill the process. Therefore we can use the “kill” command together with the PID:
kill -9 30268
The -9 signals that we want a hard kill, no interrupt, no abort, just a quick kill. This should happen immediately and another call of lsof should return nothing which means that the port is free again and we can restart our application server.