Killing an Invincible Postgres Process


Today I tried to initialize an SSH tunnel into an RDS instance. This required forwarding port 5432 for Postgres. When I initialized the SSH tunnel, I saw the following message:

Port 5432 already in use

Great, I thought. Just need to stop my local postgres server:

brew services stop postgresql@14

Tried again. Same error.

That’s odd, I thought. So I checked the status of my services:

brew services list

Postgres was stopped. Okay, there’s clearly still a process that’s using that port locally:

$> lsof -ti:5432
10723
$> ps -f 10723
  UID   PID  PPID   C STIME   TTY           TIME CMD
  503 10723     1   0 11:24AM ??         0:00.05 /opt/homebrew/opt/postgresql/bin/postgres -D /opt/homebrew/var/postgres

I tried to kill the process and create the SSH tunnel again, but it failed again! I looked up what was using the port and ANOTHER process spawned! Hm, this time out of desperation I tried to go nuclear and used kill -9 which is NOT a good idea.

Same problem, another process was spawned…

Hmm, what is that process? Seems like the Postgres server:

$> /opt/homebrew/opt/postgresql/bin/postgres --help
postgres is the PostgreSQL server.

Usage:
  postgres [OPTION]...

... More info here ...

I look up the command in the Postgres documentation. This is indeed the server. How can we control it? With the pg_ctl command!

$> pg_ctl stop -D /opt/homebrew/var/postgres

Here, -D is the data directory to the postgres db (grabbed it from the ps output above).

Now I waited… and waited…

waiting for server to shut down............................................................... failed
pg_ctl: server does not shut down

Hmm, odd. This took me of course to StackOverflow and I found one answer that seemed interesting, with 45 upvotes:

I was having the same problem...removing the launch agent solved the problem for me:

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
rm ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

What exactly is a LaunchAgent?? Turns out these are similar to Daemons, which run processes on a system level, but are specific to MacOS and allow developers to run processes on a user-session level. You can read more about them here:

https://www.techrepublic.com/article/macos-know-the-difference-between-launch-agents-and-daemons-and-use-them-to-automate-processes/

Anyway, turns out I had the same issue and unloading the LaunchAgent finally stopped the lingering process :)