怎么杀掉占用的端口
启动服务时报 EADDRINUSE: address already in use 0.0.0.0:7003,说明 7003 端口已经被另一个进程占着。
下面统一用 7003 举例,实际使用时换成自己的端口号即可。
Windows
1. 找出占用端口的进程(PID)
netstat -ano | findstr :7003
输出最后一列就是 PID。只有状态为 LISTENING 的那一行才是真正在监听的进程:
netstat -ano | findstr :7003 | findstr LISTENING
PowerShell 的等价写法(信息更清楚):
Get-NetTCPConnection -LocalPort 7003 -State Listen | Format-Table LocalAddress, LocalPort, State, OwningProcess
2. 用 PID 确认是哪个程序(别杀错)
tasklist | findstr 12345
3. 杀掉进程
taskkill /PID 12345 /F
PowerShell 一行到底:
Get-NetTCPConnection -LocalPort 7003 -State Listen | Select-Object -ExpandProperty OwningProcess | ForEach-Object { Stop-Process -Id $_ -Force }
cmd 一行搞定(在 .bat 脚本里 %a 要写成 %%a):
for /f "tokens=5" %a in ('netstat -ano ^| findstr :7003 ^| findstr LISTENING') do taskkill /PID %a /F
Linux
1. 找出占用端口的进程
lsof(最直观):
lsof -i :7003
没装的话先装:yum install -y lsof(CentOS/RHEL)或 apt install -y lsof(Debian/Ubuntu)。
ss(现代发行版自带):
ss -lntp | grep :7003
fuser:
fuser -n tcp 7003
2. 杀掉进程
kill -9 12345
常用速杀写法:
lsof -ti:7003 | xargs kill -9
fuser -k -n tcp 7003
注意
- 杀之前先看清进程名(Windows 用
tasklist,Linux 用ps -fp 12345),别把数据库、nginx 之类的服务误杀。 kill -9/taskkill /F是强杀,不给进程保存数据的机会,先试试不带-9//F的普通写法。- 如果进程被 supervisor、pm2、systemd 之类守护着,杀了会自动重启、端口又被占。这种情况要先停掉对应的服务,例如
pm2 stop <name>、systemctl stop <service>。