PG::ConnectionBad: could not connect to server: No such file or directory
--
I came across this error when attempting to start the server in my Rails API and JavaScript application.
Based on the initial Google search, I realized it was related to PostgreSQL (known as Postgres) and took the following steps to resolve the error.
Step 1: Confirm Postgres is installed locally
brew info postgresql
or
postgres -V
Step 2: Check for instances of Postgres
launchctl list | grep -i sql
Step 3: Stop any instances
brew services stop postgres
Step 4: Uninstall Postgres and remove related files
brew uninstall --force postgres
rm -rf /usr/local/var/postgres
rm -rf .psql_history .psqlrc .psql.local .pgpass .psqlrc.local
Step 5: Confirm Postgres has been removed
brew list | grep sql
This was the ah-ha moment for me! I realized I still had another version of Postgres (postgresql@12) installed. After discovering there was still another version installed, I decided to see if anything was running on port 5432, the default port for Postgres.
Step 6: Check port 5432
lsof -i :5432
Step 7: If there is anything running, kill the port
kill -9 PID (take PID from previous command)
In my case,
kill -1334
Step 8: Double check nothing is running (Postgres and PID should be gone)
lsof -i :5432
Step 9: Uninstall Postgresql@12 and related files
brew uninstall postgresql@12
rm -rf /usr/local/var/postgresql@12
rm -rf .psql_history .psqlrc .psql.local .pgpass .psqlrc.local
Step 10: Confirm the version is removed
brew list
If you don’t see Postgres in the list, it is successfully uninstalled. Run brew upgrade if instructed to do so by Homebrew.
Step 11: Reinstall Postgres
brew install postgresql
Step 12: Check it was successfully installed
brew list | grep sql
Step 13: Connect to Postgres server
brew services start postgresql
Step 14: Create a database to confirm it is working
createdb `whoami`
psql
If everything is working correctly, you should see something like this:
After successfully uninstalling and reinstalling Postgres (all versions) with Homebrew, I was able to create a database (rails db:create), migrate the schema (rails db:migrate), populate the table with my seed file (rails db:seed), and start up the server (rails s) with no issues. YAY!
This error could result from multiple causes — take time to investigate! I have listed additional solutions that worked for others below:
· https://stackoverflow.com/questions/13410686/postgres-could-not-connect-to-server
· https://techstacker.com/homebrew-uninstall-postgresql-mac/