How to kill a server from a Makefile

Learn how to kill a server process from a Makefile using the lsof command to find the PID and kill it.

If you have ever wanted to kill a server process from a Makefile so that the fresh command can be run without having to manually kill the old server, you can do it using the lsof command to find the PID of the process running on a specific port and then kill it.

Here’s a simple example of how to do this in a Makefile:

SERVER_PORT=8022

kill-server:
	@PID=$(shell lsof -t -i :$(SERVER_PORT)) && \
	if [ ! -z "$$PID" ]; then echo "killing process with PID $$PID"; kill -9 $$PID; fi

dev:
	@make kill-server
	go run .

About the Author

Ashish Anand

Ashish Anand

Founder & Lead Developer

Full-stack developer with 10+ years experience in Python, JavaScript, and DevOps. Creator of DevGuide.dev. Previously worked at Microsoft. Specializes in developer tools and automation.