Postgres could not connect to server

This sometimes happens when brew does a postgres upgrade, causing the data files to become incompatible with the new server.

In my case, it happened when upgrading from 9.3 to 9.4.

OS X/Homebrew:

Try running postgres -D /usr/local/var/postgres -- it will give you a much more verbose output if postgres fails to start. Or open the log file at /usr/local/var/log/postgres.log (/opt/homebrew/var/log/postgres.log on Mac M1) and look for the line "FATAL: database files are incompatible with server"

In my case, running rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8 removed my old databases and then reinitialized the postgres db schema. (THIS WILL DESTROY YOUR DATA)

Thanks to https://github.com/Homebrew/homebrew/issues/35240 for that solution. Full instructions for a thorough re-install can be found here: How to completely uninstall and reinstall Homebrew Postgres - Test Double Blog (Again, if you're on an M1 Mac then substitute the /opt/homebrew/var path wherever it says /usr/local/var)

After regenerating my databases (with rake db:create) everything worked fine again.

Finally, links in the comments point to this possible solution that preserves your data, but I haven't tried it: How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data - Stack Overflow


Had a similar problem; a pid file was blocking postgres from starting up. To fix it:

$ rm /usr/local/var/postgres/postmaster.pid
$ brew services restart postgresql

and then all is well.


UPDATE:

For Apple M1 (Big Sur) users, do this instead:

$ rm /opt/homebrew/var/postgres/postmaster.pid
$ brew services restart postgresql