How to solve connection error on postgresql database however postgresql seems started

On my favourite database client it’s opening a pop notification saying “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?”

At the beginning of all check the postgresql log file with command below;

tail -f /opt/homebrew/var/log/postgres.log

If output is like below;

Firstly check if the service is running properly with command below;

brew services list

If the output of command is like below

This problem generally occurs in these situations below;

1 If cause of an unexpected interruption such power failure etc. happened and postgresql so database system is closed/interrupted unexpectedly,

2 If postgresql lastly somehow started with a wrong user and the process is not responding to requests because of permission problems.

3. Database upgrade process needs to be started manually after major version upgrade from brew upgrade.

If the problem is one of those 1, and 2 above;

Execute the command below in your command line;

postgres -D /opt/homebrew/var/postgres

If the output of command like below you do not need to do anything additionally, because the recovery would be done automatically thanks to the command above;

If the output of command like below then you should kill the process with referred process id;

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

Then you should execute command below;

kill -9 548

And then restart the service with command below;

brew services restart postgresql

That’s all.