A quick way to kill a process that uses a specific port.
This is what you need if you get an
EADDRINUSE error, which says that a process can’t bind to a port because it is already in use by another process.
The most likely cause is that a development server hung up or didn’t terminate properly.
Here’s how to kill a process occupying port
kill -15 $(lsof -t -i :3000)
lsof -t -i :3000 part returns the process id (if exists) for the process that uses port 3000.
lsof is a command line utility to list open files.
From the manual (
man lsof; I love
man, it’s often quicker than a Google search):
NAME lsof - list open files […] DESCRIPTION Lsof revision 4.91 lists on its standard output file information about files opened by processes for the following UNIX dialects: Apple Darwin 9 and Mac OS X 10. FreeBSD 8., 9.0 and 1.0 for AMD64-based systems Linux 2.1.72 and above for x86-based systems Solaris 9, 10 and 11 (See the DISTRIBUTION section of this manual page for information on how to obtain the latest lsof revision.) An open file may be a regular file, a directory, a block special file, a character special file, an executing text ref- erence, a library, a stream or a network file (Internet socket, NFS file or UNIX domain socket.) A specific file or all the files in a file system may be selected by path. Instead of a formatted display, lsof will produce output that can be parsed by other programs. See the -F, option description, and the OUTPUT FOR OTHER PROGRAMS section for more information. […] -i [i] selects the listing of files any of whose Internet address matches the address specified in i. If no address is specified, this option selects the listing of all Internet and x.25 (HP-UX) network files. […] -t specifies that lsof should produce terse output with process identifiers only and no header - e.g., so that the output may be piped to kill(1). -t selects the -w option. […] AUTHORS Lsof was written by Victor A.Abell <email@example.com> of Purdue University. Many others have contributed to lsof. They’re listed in the 00CREDITS file of the lsof distribution. […]
-i :3000 looks for internet addresses that partially match
lsof give us only the process id of the process holding that file.
kill -15 $(lsof -t -i :3000) sends a regular termination signal (
-15) (similar to
CTRL-C) to the process id that
lsof -t -i :3000 returns.
$(…) opens a subshell, so
kill waits for its result.
If the termination signal was sent successfully, you’ll get a normal
0 exit code.
lsof didn’t find a file with the specified port, it’ll log:
kill: not enough arguments
If you still get an
EADDRINUSE error when you try to run your program, the program may be stuck.
Change the termination signal to
kill -9 $(lsof -t -i :3000), which immediately halts the program.