Home » Programming » Databases » How to Test Connection to PostgreSQL Database on Linux (Ubuntu/Debian/Fedora)

How to Test Connection to PostgreSQL Database on Linux (Ubuntu/Debian/Fedora)

This short tutorial will demonstrate how to test the connection to a PostgreSQL database locally and remotely from Linux.

This article is part of our series on getting started with PostgreSQL, head back to our index that lists our full PostgreSQL guide.

Testing PostgreSQL Database Connection on Ubuntu/Debian

To test connectivity to a PostgreSQL server, you’ll need the PostgreSQL client installed if it is not already. Do this by running:

sudo apt install -y postgresql-client

Then, you can use the pg_isready command to test the connection to a database:

pg_isready -d DATABASE_NAME -h HOST_NAME -p PORT_NUMBER -U DATABASE_USER    

One of the following results will be returned:

0 If the server is accepting connections normally
1 If the server is rejecting connections
2 If there was no response to the connection attempt
3 If no attempt was made (eg. due to invalid parameters)

Depending on the result you get, you can begin to troubleshoot your connection, or correct any mistyped connection details.

Testing PostgreSQL Database Connection on Red Hat/Fedora/Centos etc

The process is the same when testing from Red Hat-based distributions such as Fedora, Centos, and Rocky Linux. First, you will need to make sure you have the PostgreSQL client installed, which is included in the postgresql package:

dnf install postgresql

Then, you can run:

pg_isready -d DATABASE_NAME -h HOST_NAME -p PORT_NUMBER -U DATABASE_USER  

With the same expected results as above that will give details about the success/failure of the connection.

Other Linux Distributions

The pg_isready command detailed above will work on any Linux system where the PostgreSQL client is installed. If it is not available in your package manager, it can be installed from source – though this is not recommended if a packaged version is available.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment