When trying to connect to PostgreSQL databases on my machine via Postico, I’ve occasionally seen the following error:

could not connect to server: Connection refused
	Is the server running on host "localhost" (::1) and accepting
	TCP/IP connections on port 5432?
could not connect to server: Connection refused
	Is the server running on host "localhost" (127.0.0.1) and accepting
	TCP/IP connections on port 5432?

While my machine is in this state, if I attempt to connect via the command line instead, I’ve been met with:

the-laptop-of-a-cat:catnip sprinklesthecat$ psql postgres
psql: error: 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"?

I believe this has happened at least twice because my computer ran out of disk space. According to the Stack Overflow thread Is the server running on host “localhost” (::1) and accepting TCP/IP connections on port 5432?, this has happened to other people when their machine shut down unexpectedly, such as from a battery dying.

Failed Fix Attempts

The following attempted solutions did not work for me:

  1. restarting my computer
  2. trying to restart the Postgres service via Homebrew
  3. trying to stop and start the Postgres service via Homebrew
  4. trying to upgrade Postgres via Homebrew

Running brew services restart postgres did not work for me, nor did running brew services stop posgres followed by brew services start postgres — but it seems like they could and should.

Kill the Process

I ran:

postgres -D /usr/local/var/postgres

And saw:

FATAL:  lock file "postmaster.pid" already exists
HINT:  Is another postmaster (PID 446) running in data directory "/usr/local/var/postgres"?

I then ran:

kill 446

And saw:

LOG:  listening on IPv6 address "::1", port 5432
LOG:  listening on IPv4 address "127.0.0.1", port 5432
LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
LOG:  database system was interrupted; last known up at 2021-10-04 16:07:01 EDT
LOG:  database system was not properly shut down; automatic recovery in progress
LOG:  redo starts at 0/276EDDE8
LOG:  invalid record length at 0/276EDE20: wanted 24, got 0
LOG:  redo done at 0/276EDDE8
LOG:  database system is ready to accept connections

My terminal then sat with an open process. I hit ctrl+c, and started Postgres again via Homebrew:

brew services start postgres

Postico could establish a connection again.