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:

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:

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:

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.

This entry was posted in Apple, Linux, macOS, Tech, Tools and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">