Why You Need the PID for a Specific Port
When developing web applications, running local databases, or configuring Docker containers in Ubuntu, you will frequently encounter “Port already in use” or “Address already bound” errors. This occurs when you try to start a service (like an Nginx web server on port 80 or a Node.js app on port 3000), but a hidden background process has already claimed exclusive control over that specific network port. Before you can start your new service, you must identify exactly which rogue process is holding the port hostage and force it to close. To kill the process, you first need to find its unique Process ID (PID).
Using the lsof Command
The most efficient tool for this job is lsof, which stands for “List Open Files.” In Linux, network sockets are treated as files, meaning lsof can perfectly map network ports to the applications using them.
- Open your Terminal (Ctrl + Alt + T) or connect to your server via SSH.
- Because you are querying system-level network assignments, you must run the command with administrator privileges. Type
sudo lsof -i :followed immediately by the port number you are investigating. - For example, to find out what is running on port 3000, type:
sudo lsof -i :3000 - Press Enter and provide your password.
How to Read the Output and Kill the Process
If a process is actively using that port, the terminal will return a formatted table.
- Look at the output table. The first column (COMMAND) tells you the name of the application (e.g.,
node,python,apache2). - The second column is the PID. This is the exact number you need. Note this number (e.g.,
14523). - To forcefully terminate the process and free up the port, use the
kill -9command followed by the PID you just found. -
sudo kill -9 14523 - Press Enter. The command will execute silently.
You can verify the port is now free by running the lsof command again. If the terminal returns absolutely nothing, the port is successfully unbound and ready for your new service.