Search code examples
postgresqlnetwork-programmingpsqlhost

psql server closed the connection unexpectedly


I know there is a long standing discussion on this, however it seems I am not falling into any of the answers cited.

Ηere is my listen_address setting

cat postgresql.conf | grep -i listen
listen_addresses = '*'
cat pg_hba.conf  | grep -v '^#'
local   all             all                                     trust
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust
local   replication     all                                     trust
host    replication     all             127.0.0.1/32            trust
host    replication     all             ::1/128                 trust

This is a docker-compose setup.

What is the case here?


Solution

  • As you say, this question comes up again and again. So let me once and for all answer it. You cannot expect an explanation why this happens, because you give insufficient information for that. In fact, just figuring out what exactly is going on is half the way to the solution, so here you go.

    This message can be caused in two cases:

    1. The PostgreSQL server crashed. This is easy to determine: look at the PostgreSQL log. You would there see messages like:

      server process (PID ...) was terminated by signal ...: ...
      server process (PID ...) exited with exit code [something other than 1]
      terminating any other active server processes
      all server processes terminated; reinitializing
      database system was not properly shut down; automatic recovery in progress
      

      In that case, you have to determine the cause of the crash. These are too numerous to list, but here are a few frequent ones:

      • the Linux out-of-memory killer killed the process (terminated by signal 9: Killed)
      • you ran out of disk space in (pg_wal)
      • data corruption caused the server to crash
      • a software bug (often in a third-party extension) caused the server to crash
    2. There is a network problem. If that is the case, you will see nothing in the PostgreSQL log, or perhaps a message like

      unexpected EOF on client connection with an open transaction
      could not receive data from client: Connection reset by peer
      

      Again, there are several possible causes, but the most likely cause is a mis-configured firewall, router or other network component that drops TCP connections that idle for too long. Very often, it is enough to configure TCP keepalive on the database client or server to get rid of the problem.