← Back to Blog

Free a port with lsof and start a fresh server

Developer NotePublished May 20, 2023Updated September 23, 20261 min read
macOSLinuxCommand LineDebugging

TLDR

kill $(lsof -t -iTCP:3000 -sTCP:LISTEN)

Replace 3000 with your development server’s port. This sends a termination request to every process listening on that TCP port. Once the old server exits, start your server again.

Use it for a local development server you’re happy to stop. The command works in Bash or zsh on macOS and Linux with lsof installed.

Why I use it

I found this command when a server process had become detached and was still holding the port I needed. Tools sometimes bug out. I didn’t want to spend time tracking down the old process just to start a new instance.

I still use lsof for this quick fix. It gets the old server out of the way so I can start a fresh one. Why the process was left behind can wait.

What the command does

lsof -t returns process IDs. -iTCP:3000 -sTCP:LISTEN limits the result to TCP listeners on port 3000, excluding clients connected to the server. The shell runs the command inside $(...) and passes its output to kill. lsof manual

Ordinary kill sends SIGTERM, which gives the process a chance to clean up before exiting. If the old server still won’t stop after a moment, force it:

kill -9 $(lsof -t -iTCP:3000 -sTCP:LISTEN)

-9 sends SIGKILL. The process cannot catch it to save state or perform application cleanup. Signal behavior

Browse all writing →