Getting DBConnection.ConnectionError connection refused error

Environment:

  • Windows 10

  • Using WSL2 with Ubuntu Server via Windows Terminal to run setup

  • Database URL: ecto://postgres:postgres@localhost/chat_api_dev

  • Error: ** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused
    (db_connection 2.2.2) lib/db_connection/connection.ex:87: DBConnection.Connection.connect/2
    (connection 1.0.4) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib 3.13) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
    Last message: nil
    State: Postgrex.Protocol
    ** (Mix) The database for ChatApi.Repo couldn’t be created: killed

I have validated that postgresql service is running in WSL2 by doing “sudo service postgresql status” which returns “13/main (port 5432): online”

I also run “netstat -an | grep 5432” which validates the port is listening

Also do “telnet localhost 5432” which connects fine

When you netstat can you output the IP it binds to? (If that is also a localhost ip it does not allow access from outside the wsl2 vm but can be accessed from inside the vm)

Comparing WSL 2 and WSL 1 | Microsoft Docs You could try to access it on it’s own VM IP to see if that works.

If it is all working from inside WSL2 it could also be a firewall rule blocking going from outside to WSL2.

I was curious about that, still understanding the mechanics of WSL2. I have a Postgres service on my Windows machine that is not the same (from my understanding) as as the one running within the WSL2.

When I do the netstat mentioned above this is what it outputs:
tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN
unix 2 [ ACC ] STREAM LISTENING 20997 /var/run/postgresql/.s.PGSQL.5432

I did try to setup the Postgres instance on Windows and access that via ip bu then receive the “non-existing domain - :nxdomain” error.
I have an inbound windows firewall rule to allow all incoming traffic from the WSL2 IP to port 5432

WSL2 IP when running ifconfig: 172.24.95.116
Windows IPv4: 172.24.80.1

Did you already try to use that 172.24.95.116 ip (the WSL2 ip) for the ecto connect string instead of localhost?

I did, if I do that I receive the following

10:53:14.808 [error] GenServer #PID<0.1557.0> terminating
** (DBConnection.ConnectionError) tcp connect (172.24.95.116:5432): non-existing domain - :nxdomain
    (db_connection 2.2.2) lib/db_connection/connection.ex:87: DBConnection.Connection.connect/2
    (connection 1.0.4) lib/connection.ex:622: Connection.enter_connect/5
    (stdlib 3.13) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
Last message: nil
State: Postgrex.Protocol
** (Mix) The database for ChatApi.Repo couldn't be created: killed

Update: Never resolved the issue. Just switched to running the app on my Windows machine instead of in WSL2.