TL;DR If you’re on OS X, installed Postgres with homebrew, and are receiving errors asking if your Postgres server is running locally and accepting connections, check that your PGHOST is configured for localhost

In the never-ending battle that is Postgres versus Mac OS X, which I’ve written about before, Postgres narrowly claimed a victory tonight but four little words and a helpful Stack Overflow answer saved the day.

I was digging into a Rails app and firing up Postgres for one of the first few times on a computer running OS X 10.8.4. When I tried to run any of the rake db commands I received what unfortunately may be a familiar error for any dev trying to run Postgres on OS X:

could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

Seeing as how I’d stared down the Postgres beast before I was confident this would be a relatively quick yak-shave and tried to fire up Postgres on the command line. Somewhat surprisingly it worked and I was able to create and edit tables and roles without any problem.

Next I did a check for running processes via ‘ps auxwww | grep postgres’ and I could see that all the expected postgres processes were there. Hmmm….

The next line in the stack trace directed me down into the gem file…

../gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `initialize'

…but when I opened that I immediately spied a splat operator in the method that meant the offending argument could really be anything…

def connect
      @connection = PGconn.connect(*@connection_parameters)

So then I took a step back and wandered back up to the original error. What stuck out to me there was the very specific socket in the error: .s.PGSQL.5432.

A Google search then led me to my solution, which was to configure my PGHOST to point to localhost. This could be done in one of two places, either by adding 'export PGHOST=localhost’ to a file that handled some of my other variables (like my ~/.bash_profile), or by adding host:localhost to the Rails app’s config/database.yml file (for the test and development environments.

I ended up setting the variable in my .bash_profile because when I fired up an old Sinatra app that used Postgres I received similar errors. Setting the variable system-wide took care of those errors as well.