Find (and kill) process locking port 3000 on Mac

2019-01-02 16:10发布

How do I find processes that listens to/uses my tcp ports? I'm on mac os x.

Sometimes, after a crash or some bug, my rails app is locking port 3000. I can't find it using ps -ef... How do I find the stupid thing and kill it, brutally... ?

When doing

rails server

I get

Address already in use - bind(2) (Errno::EADDRINUSE)

2014 update:

To complete some of the answers below: After executing the kill commands, deleting the pid file might be necessary rm ~/mypath/myrailsapp/tmp/pids/server.pid

标签: macos process
24条回答
流年柔荑漫光年
2楼-- · 2019-01-02 16:39

One of the ways to kill a process on a port is to use the python library: freeport (https://pypi.python.org/pypi/freeport/0.1.9) . Once installed, simply:

# install freeport
pip install freeport

# Once freeport is installed, use it as follows
$ freeport 3000
Port 3000 is free. Process 16130 killed successfully
查看更多
唯独是你
3楼-- · 2019-01-02 16:40
lsof -P | grep ':3000' | awk '{print $2}'

This will give you just the pid, tested on MacOS.

查看更多
呛了眼睛熬了心
4楼-- · 2019-01-02 16:40

Find PID and kill the process.

lsof -ti:3000 | xargs kill
查看更多
素衣白纱
5楼-- · 2019-01-02 16:41

To forcefully kill a process like that, use the following command

lsof -n -i4TCP:3000 

Where 3000 is the port number the process is running at

this returns the process id(PID) and run

kill -9 "PID"

Replace PID with the number you get after running the first command

For Instance, if I want kill the process running on port 8080

查看更多
裙下三千臣
6楼-- · 2019-01-02 16:43

Here's a helper bash function to kill multiple processes by name or port

fkill() {
  for i in $@;do export q=$i;if [[ $i == :* ]];then lsof -i$i|sed -n '1!p';
  else ps aux|grep -i $i|grep -v grep;fi|awk '{print $2}'|\
  xargs -I@ sh -c 'kill -9 @&&printf "X %s->%s\n" $q @';done
}

Usage:

$ fkill [process name] [process port]

Example:

$ fkill someapp :8080 node :3333 :9000
查看更多
残风、尘缘若梦
7楼-- · 2019-01-02 16:45

I made a little function for this, add it to your rc file (.bashrc, .zshrc or whatever)

function kill-by-port {
  if [ "$1" != "" ]
  then
    kill -9 $(lsof -ni tcp:"$1" | awk 'FNR==2{print $2}')
  else
    echo "Missing argument! Usage: kill-by-port $PORT"
  fi
}

then you can just type kill-by-port 3000 to kill your rails server (substituting 3000 for whatever port it's running on)

failing that, you could always just type kill -9 $(cat tmp/pids/server.pid) from the rails root directory

查看更多
登录 后发表回答