Docker container times out when connecting to PostgreSQL on the VPS host
Asked by
MellowCedar42
I'm installing Psono on a VPS and running PostgreSQL directly on the host rather than in a container. PostgreSQL works from the VPS itself and from my home network using psql with the VPS address and custom port. However, when the application inside a Docker container tries to connect, the connection hangs and eventually times out. The container can reach external websites, and network scanning shows that it can connect to the VPS port. What PostgreSQL or Docker networking settings should I check?
Answers
A timeout usually points to routing or a firewall rather than an incorrect password. Test the exact database endpoint from inside the container with a TCP tool, for example `nc -vz HOST_ADDRESS PORT`, and compare it with the address used by the application. Confirm that PostgreSQL is bound to that address, the port is open, and the Docker networkโs source range is permitted. Also check the PostgreSQL logs while making a connection attempt; if no log entry appears, the traffic is being blocked or sent to the wrong address.
Reply to this answer
Check both PostgreSQLโs network listener and its client authentication rules. PostgreSQL must listen on an address reachable from Docker, not only on 127.0.0.1. In postgresql.conf, verify that listen_addresses includes the VPS address or '*' and then reload or restart PostgreSQL. In pg_hba.conf, add a rule for the Docker subnet, such as `host psono psono 172.17.0.0/16 scram-sha-256` or the actual subnet used by the container network. A rule limited to 127.0.0.1 only permits local host connections. Also make sure the VPS firewall allows the database port from that Docker subnet.
Reply to this answer
The containerโs `localhost` refers to the container itself, so it cannot reach PostgreSQL that way unless the container shares the host network. On Linux, you can either connect to the hostโs reachable IP address, use the Docker bridge gateway, or run the container with host networking and then connect to localhost. The simplest approach is usually to use the host or bridge-gateway address in the applicationโs database settings and allow that Docker network in pg_hba.conf.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions