ubuntu – Can connect to Postgres remotely, but not from localhost

I’m having some trouble connecting to my server’s Postgres database from an API that is running on the same machine as Postgres.

I’ve been following this Google Cloud Guide to set it up.

  1. I’ve edited pg_hba at sudo nano /etc/postgresql/12/main/pg_hba.conf.
    I’ve added my own IP at the bottom of it so I can connect to it from my machine, and ensured that the file allowed for localhost connections as well:
# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
host    all             all               md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
  1. I edited /etc/postgresql/12/main/postgresql.conf and set listen_addresses = '*'.

  2. I’ve restarted the server.

I can now successfully connect remotely (from my machine) by using the string:

postgres://(username):(password)@(ip of server):5432/(database name)

However, if I try to use the following with an API that is running on the same server:

postgres://(username):(password)@<localhost or 127.0.01>:5432/(database name)

No connection can be established. I don’t actually get an error, which leads me to believe I either

  1. Have the string written wrong
  2. I’m missing something to allow that connection

Any help would be really appreciated. I’m running this on a Gcloud Compute Engine Ubuntu instance, although I don’t think that makes much difference. I have set all the rules correctly in my firewall settings as well.