目录

怎么杀掉占用的端口

启动服务时报 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

注意