Search code examples
postgresqldockerpsql

cannot connect to postgres docker container from host os with psql


Problem

  • Im not able to connect to postgres db inside docker container from host. Im making simple crud app with node.js so managing db from inside of container doesn't come into play.

Solutions I've tried

  • Im exposing port from container
  • running psql as postgres local user on host os
  • redirecting 5432 to different local port

Im running postgres container with: docker run --name postgres -p 5432:5432 -e POSTGRES_PASSWORD=secret -e POSTGRES_USER=postgres -d postgres

when running psql -h (localhost or 127.0.0.1) -p 5432 -U postgres I get "psql: error: connection to server at "127.0.0.1", port 5432 failed: server closed the connection unexpectedl This probably means the server terminated abnormally before or while processing the request."

additional info: docker container ps -a -> f596d7350e9c postgres "docker-entrypoint.s…" 6 seconds ago Up 5 seconds 0.0.0.0:5432->5432/tcp, :::5432-> 5432/tcp postgres

ss -lntp -> LISTEN 0 32 192.168.100.1:53 0.0.0.0:* LISTEN 0 4096 0.0.0.0:5432 0.0.0.0:* LISTEN 0 4096 [::]:5432 [::]:*

I know there are bunch of similar questions asked prior to similar problem but they don't seem to solve problem in my case. ex: Connecting to Postgresql in a docker container from outside

I've been trying to fix this issue for past 2 days im stuck at this point.


Solution

  • I've ran into this exact same issue some years ago.

    The fix is to adjust your pg_hba.conf to allow your docker ip address in.

    See: Docker Rundeck + local Postgres