PG::ConnectionBad - could not connect to server: Connection refused PG::ConnectionBad - could not connect to server: Connection refused ruby ruby

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/.
  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


You would need to restart the Postgresql Server.

If you are using ubuntu you can restart Postgresql by following command

sudo service postgresql restart


I have managed to solve the problem by following the Chris Slade's answer, but to restart the server, I had to use the following commands:

launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plistlaunchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

that I found here (pjammer's answer down at the bottom)