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).
- 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/
. - 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"?
- If so,
rm postmaster.pid
Restart your server. On a mac using launchctl (with homebrew) the following commands will restart the server.
launchctl unload homebrew.mxcl.postgresql.plist launchctl load -w homebrew.mxcl.postgresql.plist
OR on newer versions of Brew
brew services restart postgresql
This issue comes when postgres doesn't shut down properly. Here is how I resolved this issue in three simple steps.
Step 1: Go to your postgres directory
Mac Users will find this in /usr/local/var/postgres
, others might look at /usr/var/postgres/
.
Step 2: Remove .pid
file by running this command.
rm postmaster.pid
Step 3: Restart your server
Mac Users
brew services restart postgresql
Linux Users
sudo service postgresql restart
Finally restart your app and you are good to go.
You would need to restart the Postgresql Server.
If you are using ubuntu you can restart Postgresql by following command
sudo service postgresql restart