1

I am running PostgreSQL on my localhost on MacOS. Every once in a while (~ every 5 times I reboot the computer), I face the following error when I try to connect to my local database instance:

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?

When this happens, I have gotten used to the practice of opening the terminal, then running

 rm -f /usr/local/var/postgres/postmaster.pid

which allows me to connect to the database. According to the documentation, having an old .PID file in the data directory "confuses" postgres and so it must be removed.

My question is, why must be this done intermittently and can one automate the removal of old .pid files ? Please note that brew services restart postgres does not resolve the issue - only the removal of the old .pid file works. Any advice here would be greatly appreciated!

1
  • What does the log file say?
    – jjanes
    Apr 5, 2021 at 16:22

1 Answer 1

0

The postmaster.pid file is one of the measure that PostgreSQL takes to prevent starting multiple database servers on the same data directory at the same time (which would cause data corruption).

If you start the PostgreSQL server and there is a postmaster.pid file present, PostgreSQL checks if there is a process running with the process with the process ID from the PID file. If not, PostgreSQL will ignore the obviously stale file and start anyway. Otherwise, it will refuse to start.

The correct solution is to see that the database is shut down cleanly when you turn off the machine. A clean shutdown will remove postmaster.pid. This will also save you the time to perform crash recovery on the PostgreSQL database.

2
  • What if postmaster.pid is indeed removed after a clean shutdown, and yet it complains that it is there? (That is, getting FATAL: lock file "postmaster.pid" already exists, but there is no trace of postmaster.pid on the whole system before starting the cluster again.)
    – toraritte
    May 4 at 17:26
  • 1
    Start it with strace -o logfile /path/to/postgres --single -D /path/tp/datadir postgres and look in logfile where it finds that file. May 4 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.