Terminating process that occupy the specific port

In a nutshell:

1. cmd.exe
2. netstat -aon | findstr :port 
(e.g. netstat -aon | findstr :5001)
3. taskkill /F /PID XXXXX

This post is about kill the process that occupying port that we want to use. Sometimes when you developing app on your local machine you can encounter port blocked. In my cases, these were ports 4200 and 5001. For example after using ng start command for start Angular frontend application or dotnet run command for backend app in command line. It usually happens when you close console without stopping application. So to release once again this port you can kill process that occupied it. We will use netstat and taskkill commands to solve this problem.

  • Example with dotnet run and port number 5001
    When port is blocked, and we want to start our application that using ours port 5001 (https://localhost:5001) then we get exception with text:

    “Unable to start Kestrel.”
    “Failed to bind to address address already in use.
Visual Studio 2019 exception and Windows cmd

To solve problem with occupied port we can use netstat command in cmd. There are additional parameters to get clear results. It displays listening all connections, address, ports and PID (Process IDentifier) associated with each connection.

netstat -a -o -n
or slightly improved command:
netstat -aon | findstr :port (e.g. netstat -aon | findstr :5001)

Windows cmd – netstat command

I used netstat and found PID 36000 that associated with my port:

Port 5001 and PID 36000

Then I terminated this process using taskkill command:

taskkill /F /PID XXXX (where XXXX is appropriate PID)

Windows cmd – taskkill command

So now process is released, and we can start our app.

  • Second example with ng serve and port number 4200
    When port is blocked, and we want to start our application that using our port 4200 (http://localhost:4200) then we get warning with text:

    “An unhandled exception occurred: Port 4200 is already in use. Use ‘–port’ to specify a different port.”
Visual Studio Code – exception

For example when trying close app in MINGW64 console appears warning that application is running. On Windows command line there is not this warning, so it is easier to get this problem, and we can simulate it.

MINGW64 console

netstat -aon command:

Port 4200 and PID 1628

taskkill /F /PID 1628 command:

Terminating PID 1628

The process has been successfully terminated.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: