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 https://127.0.0.1:5001: address already in use.“
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)
I used netstat and found PID 36000 that associated with my port:
Then I terminated this process using taskkill command:
taskkill /F /PID XXXX (where XXXX is appropriate PID)
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.”
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.
netstat -aon command:
taskkill /F /PID 1628 command:
The process has been successfully terminated.