[Debugging] postgresql 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’?

Postgresql version 14.7 installed in my macbook through homebrew raised an error that returned the following error message while running psql on terminal.

psql: error: connection to server on socket "/tmp/.s.pgsql.5432" failed: no such file or directory

Found out that this is a very common error that comes up if you depend on postgresql service on your own device. This is usually caused for the following reasons:
– Postgresql is running on a different port but your application is trying to connect to port 5432
– Unexpected shutdown of postgresql service

In my case, it was the unexpected shutdown.

Steps to fix:

  • Check if postgresql is up
    pgrep -l postgres
    if there is no output, postgresql is not running
  • Try starting postresql service
    brew services start postgresql
    check again if the service is up by running
    pgrep -l postgres
  • If there is still no output, we will have to check log. Lets head to the following directory to check for log.
    cd /usr/local/var/log
    Depending on your version of postgres, you will find your log as shown below:
    list of files in log folder
  • Follow your log to check for the error
    tail postgresql@14.log
  • If you see an error regarding postmaster.pid file, your case is similar.
    This states that postgresql service was not shutdown properly and the file postmaster.pid file still consists of the process id the last time the service was running. If this is not the case, you will need to debug more regarding the error.
    postmasterid
  • Head over to the installation directory and check for the contents of postmaster.pid
    cat /usr/local/var/postgresql@14/postmaster.pid
    The file should consist of the stale process id, deleting the file should work.
  • Delete the file postmaster.pid and start postgresql again
    rm /usr/local/var/postgresql@14/postmaster.pid
    brew services start postgresql
    pgrep -l postgres
  • You should now see similar output

Your postgresql service is now running.