How can a Docker container connect to PostgreSQL running on the VPS host?

0
0
Asked By MellowCedar47 On

I'm installing Psono on a VPS and running PostgreSQL directly on the host rather than in a container. PostgreSQL works when I connect locally on the VPS and remotely from my home network with `psql -U psono -p PORT -h VPS_IP`, but the application inside its Docker container hangs and eventually times out when connecting.

The container can reach external websites and `nmap` shows that it can connect to the relevant host and port, so basic networking appears to work. I'm new to Docker and would appreciate help identifying what needs to be configured for the container to reach PostgreSQL on the host. My PostgreSQL access rules currently include localhost entries and a broader `host all all 0.0.0.0/0 md5` rule.

2 Answers

Answered By NorthVale22 On

On Linux, Docker normally puts containers on a bridge network. You can either connect to the host through its reachable VPS address, or add a host mapping such as `host.docker.internal:host-gateway` in the Compose file and use `host.docker.internal` as the database hostname. Another option is `network_mode: host`, which makes the container share the host network and allows `localhost` to refer to the VPS, but that reduces network isolation and is usually not necessary.

Also verify the actual container network and gateway with `docker inspect`, and test from the container using `psql` or `nc -vz HOST PORT`. A successful external `nmap` scan does not prove that PostgreSQL accepts the container’s source address.

MellowCedar47 -

I’m not using a VPN; the VPS is the only host involved. I’ll test the Docker gateway or host mapping rather than assuming that `localhost` points to the VPS.

Answered By PixelHarbor8 On

Check both PostgreSQL configuration and the host firewall. `pg_hba.conf` must allow connections from the Docker bridge subnet, not just `127.0.0.1` and `::1`. For example, if Docker uses `172.17.0.0/16`, add a rule such as `host psono psono 172.17.0.0/16 scram-sha-256` (or the authentication method your setup uses). Also make sure `listen_addresses` in `postgresql.conf` includes the host’s Docker-facing address, then reload or restart PostgreSQL.

From inside the container, connect to the VPS address that is reachable from the container, not automatically to `localhost`; inside a container, `localhost` refers to the container itself. If you use a broad `0.0.0.0/0` rule, restrict it to the Docker subnet and trusted networks instead of exposing PostgreSQL unnecessarily.

MellowCedar47 -

The existing rules were mainly for localhost, so I’ll add the Docker subnet explicitly and check `listen_addresses` and the VPS firewall as well.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.