Debugging a missing PostgreSQL connection on macOS

Mike Burns
Edited by Aji Slater

If you have an Apple laptop that you do development on, or otherwise need to run a local app on, you might see this error sometimes:

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

This indicates that PostgreSQL is no longer running. If it was previously working fine, we can fix that. Let’s dig in.

You’re going to need the Terminal app.

First up, using pgrep(1) to determine whether Postgres is running:

% pgrep -l postgres

If that gives you no output, that means Postgres isn’t running. Great, we can work with that.

If that does give you output, this blog post isn’t for you. You have another issue than the one we’re solving here, and you might have better luck on Stack Overflow.

Let’s try starting it using brew services

% brew services start postgresql

If this command’s output included something to the tune of

Warning: Formula postgresql was renamed to postgresql@14

any further brew commands will have to reference postgresql with an included version number. We can see which version we have installed with:

% brew list | grep postgresql

The rest of the instructions here will use @14, but your version might be different.

After we’ve started with brew services, we’ll check to see if it’s running:

% pgrep -l postgres

Still not running? Check the logs with a shell [command sustitution] and tail(1):

% tail $(brew --prefix)/var/log/postgresql@14.log

You may see an error about a file named postmaster.pid:

FATAL:  lock file "postmaster.pid" already exists

This indicates that Postgres had not been shut down cleanly, for any number of reasons. The first line of the postmaster.pid file is the process identifier of what once was Postgres. Let’s see what that is now, using ps(1):

% ps ax | grep $(head -1 /usr/local/var/postgres/postmaster.pid)

If you see something about Postgres in the output, then your issue is something deeper and you’ll need to debug more thoroughly before proceeding. But if your output is empty, or you see something unrelated to Postgres, your PID file was stale and we can remove it.

Remove the stale PID lock then start the server again:

% rm $(brew --prefix)/var/postgresql@14/postmaster.pid
% brew services start postgresql@14
% pgrep -l postgres

Postgres should now be running.