Search code examples
postgresqlintellij-ideaconnectionlocalhost

Can't connect to local Postgres in IntelliJ IDEA


This seems like it should be a very basic problem to fix, but it's driven me to the brink of madness and cost me days of work.

I'm trying to run Java integration tests locally but they're failing due to a PSQLException in connecting. In my terminal, I'm pinging localhost fine and I can successfully telnet to 5432. I can get to the local DB using Postico as well. To try to get at this problem, I'm trying to configure a database within IDEA. It's pretty elementary. The URL is jdbc:postgresql://localhost:5432/postgres and all the other settings match my successful Postico configuration. I haven't changed anything in the Drivers tab; the PostgreSQL driver is 42.6.0, the latest stable. (I tried a few older ones, including all the way back to 9.x; no dice.) We use PostgreSQL 13.10.

This is especially puzzling because everything was fine last week, then I opened up my computer on Monday and everything was broken. I have 2023.2 on my Mac, but this issue was happening before that. I even completely uninstalled IDEA and deleted all of the JetBrains/IDEA settings from ~/Library to start again, but no change. Hoping to find some insights here, as my team and I are completely out of ideas short of an exorcism. Thanks.

Additional info added from comments:

/etc/hosts, excluding comments, is:

127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost

There isn't much clueful in the logging. I see only "The connection attempt failed" in the UI. That message is associated with DatabaseConnectionEstablisher, ID 08001.

sudo lsof -i :5432 yields:

COMMAND   PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
com.docke 535  [me]  223u  IPv6 0xdc13b7dc139e8629      0t0  TCP *:postgresql (LISTEN)

Solution

  • According to lsof output the database server is listening on IPv6 interface instead of IPv4.

    To force IntelliJ IDEA/DataGrip use IPv6 you can add the following in Help | Edit Custom VM Options and restart the IDE:

    -Djava.net.preferIPv4Stack=false
    -Djava.net.preferIPv6Addresses=true
    

    You may also need to add the same in the data source Advanced settings, VM options field and in the VM Options for your tests / Java apps.