Skip to content

Instantly share code, notes, and snippets.

@codewithgun
Last active May 17, 2021 18:24
Show Gist options
  • Save codewithgun/3a6a99f80defbf26804401cc8a86bf02 to your computer and use it in GitHub Desktop.
Save codewithgun/3a6a99f80defbf26804401cc8a86bf02 to your computer and use it in GitHub Desktop.
How to configure postgres to receive external/remote request

Unable to connect Postgresql from client

There was several reasons causes client unable to connect to Postgres database.

First, run sudo systemctl status postgresql to check whether the database is running.

If the output shows status: active, it shows that the database is up and running. The problems might due to authentication, listening port, or firewall.

In Postgres, there was few type of authentication methods. However, most of the time, the authentication will be password authentication or local socket authentication.

By default, when request come from localhost, peer (local socket authentication) will be used automatically. Local socket authentication authenticate the user based on the current logged in UNIX/LINUX user. This is the reason why you can access to postgres after switch to postgres user sudo su postgres, then run psql to access to the database.

Now, let's start fix it.

First, switch to postgres user by running sudo su postgres in terminal. After that, access the postgres database by running psql. Then, change the password of postgres user by running \password postgres then enter your new password.

Second, if you are accessing postgresql remotely, please make sure that postgres database doesn't blocking the accessing ip address. Open up postgres_hba.conf by running vi /etc/postgres/{version}/main/pg_hba.conf. After that, add host all all 127.0.0.1/32 md5

Remember to change 127.0.0.1/32 to your ip address. Eg: 218.11.66.102/32

This will allow remote request to postgres database.

Last but not least, we going to configure postgres to listen request coming from all ip address instead of localhost only. Open up postgresql.conf by running vi /etc/postgres/{version}/main/postgres.conf. Then, change #listen_addresses = 'localhost' to listen_addresses = '*'

Last, remember to restart your postgres database by running sudo systemctl restart postgresql. If still doesn't work, try run sudo ufw status to check whether the firewall is enabled. If it wasn't enabled, run sudo ufw allow postgres to make the firewall unlock the remote request for postgres using port 5432.

Now, you should be able to connect to your postgres database remotely.

You may troubleshoot whether the postgres is listening on port 5432 by running telnet {ip address} 5432. If you get connection closed by foreign host, means the database is running and listening on port 5432, this narrow down the area for troubleshooting to authentication and postgres configuration file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment