PG::ConnectionBad – could not connect to server: Connection refused

It could be as simple as a stale PID file. It could be failing silently because your computer didn’t complete the shutdown process completely which means postgres didn’t delete the PID (process id) file.

The PID file is used by postgres to make sure only one instance of the server is running at a time. So when it goes to start again, it fails because there is already a PID file which tells postgres that another instance of the server was started (even though it isn’t running, it just didn’t get to shutdown and delete the PID).

  1. To fix it remove/rename the PID file. Find the postgres data directory. On macOS using homebrew it is in /usr/local/var/postgres/, or /usr/local/var/log/ other systems it might be /usr/var/postgres/. On M1, it might be /opt/homebrew/var/postgresql.
  2. To make sure this is the problem, look at the log file (server.log). On the last lines you will see:

FATAL: lock file “postmaster.pid” already exists
HINT: Is another postmaster (PID 347) running in data directory “/usr/local/var/postgres”?

  1. If so, rm postmaster.pid
  2. Restart your server. On a mac using launchctl (with homebrew) the following commands will restart the server.brew services restart postgresql

OR on older versions of Brew

    launchctl unload homebrew.mxcl.postgresql.plist  
    launchctl load -w homebrew.mxcl.postgresql.plist

Leave a Comment