Skip to main content

Linux 如何查看某个端口对应的进程并kill?

· 3 min read

线上排查端口冲突时,查进程、杀进程、防复活是三个标准动作。

  • 查端口lsof -i :端口 一把梭,比 netstat/ss 更直观。
  • 一行 killkill -9 $(lsof -ti :端口),查 PID 和杀进程一条命令搞定。
  • 杀了又活大概率是守护程序自动拉起,先查 systemd/supervisor/pm2。
  • 根本解法:直接停掉守护服务再操作,从源头控制,不跟重启赛跑

lsof 一把梭

服务启动报 address already in use,先看谁占了端口:

lsof -i :8080

输出长这样:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 12345 kimi 23u IPv4 123456 0t0 TCP *:8080 (LISTEN)

关键字段就两个:COMMAND——谁占的,PID——进程号。拿到 PID 直接 kill:

kill -9 12345

lsof vs netstat vs sslsof -i :端口 最直觉,不用加过滤就能同时看到进程名和 PID。ss -tlnp | grep 端口 也能查,但输出信息密度不如 lsof。日常排查,lsof 够用。

一行命令解决

懒得先查 PID 再 kill?$() 直接把 PID 喂给 kill:

kill -9 $(lsof -ti :8080)

-t 让 lsof 只输出 PID(去掉了表头和其他列),-i 按端口过滤。查 + 杀,一条命令搞定。

xargs 写法等价,挑顺手的用:

lsof -ti :8080 | xargs kill -9

xargs 做了什么? — 管道 | 传的是标准输入(stdin),不是命令行参数。kill 这类命令只认参数,不读 stdin,直接 lsof -ti :8080 | kill 是不行的。xargs 就是中间的"翻译官"——把 stdin 的内容转成后面命令的参数再执行。所以 lsof -ti :8080 | xargs kill -9 实际等于 kill -9 12345

杀了又活了?查守护进程

kill -9 之后进程立刻复活——说明有个守护程序在自动拉起。直接 kill 治标不治本,得找到幕后的那个进程。

按场景排查:

守护程序停服命令常见场景
systemdsystemctl stop xxx大多数 Linux 发行版
supervisorsupervisorctl stop xxxPython/Go 常驻服务
pm2pm2 stop xxxNode.js 应用
Dockerdocker stop xxx容器化部署

不确定是哪种?看目标进程的父进程:

ps -o ppid= -p <PID> | xargs ps -o comm= -p

父进程是 systemd → systemd 管着;是 supervisord → supervisor 管的;是 containerd → Docker 容器。找到守护程序,停掉它,再操作。

小结

日常三板斧,记住就行:

  • 查进程 → lsof -i :端口
  • 一行 kill → kill -9 $(lsof -ti :端口)
  • 杀完复活 → systemctl stop / supervisorctl stop / pm2 stop

每次搜 Stack Overflow 都看到同样的回答,不如存脑子里。