Category: All posts
Jan 20, 2025
Posted by
Semab Tariq
Let’s imagine a few scenarios:
In all these scenarios, the first question that might come to mind is: How can I check if PostgreSQL is running and test the connection?
Don’t worry! You are not alone! 😊 In today’s blog, I’ll guide you through various methods to test a PostgreSQL connection, which will help you tackle these and other similar scenarios.
(If you have not done so already, install PostgreSQL by following the community guidelines for your preferred operating system here.)
There are several ways to check your PostgreSQL connections. To make things clearer, I have divided them into three sections:
Let’s explore them one by one.
Let’s explore the different ways PostgreSQL can help determine if it is ready and available for new connections.
pg_isready
PostgreSQL includes a built-in utility called pg_isready
, which is available after installation. This tool is the most commonly used to check if PostgreSQL is ready to accept connections.
pg_isready -h <HOST_NAME> -p <PORT_NUMBER> -d <DATABASE_NAME> -U <DATABASE_USER>
To use pg_isready
PostgreSQL on port 5430 is not responding, specify the required values based on your PostgreSQL installation:
<HOST_NAME>
: This can be localhost
or the public or private IP address of the server where PostgreSQL is installed.<PORT_NUMBER>
: The port number on which PostgreSQL is listening (default is 5432).<DATABASE_NAME>
: The name of the database you want to check.<DATABASE_USER>
: The username for the database connection.Once you have replaced the placeholders with the appropriate values, execute the command to check the PostgreSQL server’s availability.
The first command shows that PostgreSQL on port 5434 is accepting connections. The second command indicates that PostgreSQL on port 5430 is not responding, meaning it’s either not running or unreachable.
/Library/PostgreSQL/15/bin/pg_isready -h localhost -p 5434 -d postgres -U postgres
localhost:5434 - accepting connections
/Library/PostgreSQL/15/bin/pg_isready -h localhost -p 5430 -d postgres -U postgres
localhost:5430 - no response
psql
—PostgreSQL interactive terminalAnother common way to check if PostgreSQL is ready to accept connections is by using the psql
command-line utility, which is also included during the PostgreSQL installation. It allows you to attempt a connection to the server and provides feedback on whether the server is available.
psql -h <HOST_NAME> -p <PORT_NUMBER> -d <DATABASE_NAME> -U <DATABASE_USER>
Similar to pg_isready
, to use psql
, specify the required values based on your PostgreSQL installation.
Note: After executing the above command with the correct installation parameters, you will be prompted to enter the password for the user specified with the -U
switch. If the service is running, psql
will then take you to the PostgreSQL terminal. However, if the service is down, you won't be prompted for the password, which indicates that the service is unavailable or the credentials are incorrect.
If the connection is successful, you will see a message similar to this, indicating that you have connected to the database:
/Library/PostgreSQL/15/bin/psql -h localhost -p 5434 -d postgres -U postgres
Password for user
postgres:psql (15.4, server 13.18)
Type "help" for help.
postgres=# \q
If there’s an issue connecting, an error message will appear, such as:
/Library/PostgreSQL/15/bin/psql -h localhost -p 5430 -d postgres -U postgres
psql: error: connection to server at "localhost" (::1), port 5430 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5430 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
This helps you determine whether the PostgreSQL server is accepting connections and if the specified credentials are correct.
Note: Both utilities mentioned above are available on all operating systems in the <POSTGRESQL_INSTALLATION_DIRECTORY>/bin
directory.
listen_address
parameter inside postgresql.conf file If you want to check whether your PostgreSQL server can accept connections from outside the localhost
, you need to verify the listen_addresses
parameter in the postgresql.conf file.
This parameter defines the IP addresses that PostgreSQL listens to for incoming connections.
To check and modify the listen_addresses
parameter, open the postgresql.conf file, usually located in the PostgreSQL data directory. Look for the listen_addresses
line and verify or update its value.
isten_addresses = '<ADDRESS>'
<ADDRESS>
: This can be set to the following parameters:
'localhost'
: PostgreSQL will only accept connections from the local machine.'192.168.1.100'
): PostgreSQL will accept connections from the specified IP address.'*'
: PostgreSQL will accept connections from any IP address.Note: After updating the listen_address
parameter, a restart is required for the PostgreSQL server.
We have covered some built-in methods within PostgreSQL for checking database connections. Now, let’s shift our focus to external tools and see how they can help achieve the same purpose.
We can determine if PostgreSQL is running and accepting connections by checking the status of the PostgreSQL service itself. If the service is active (running), PostgreSQL is operational and ready to accept connections; if it’s stopped or disabled, the database won’t be available for connections.
On macOS, you can use the launchctl
command to check the status of PostgreSQL services.
sudo launchctl list | grep postgres
321 0 postgresql-13
322 0 postgresql-15
324 0 postgresql-16
In the example above
On Linux, the service
utility can be used to check if PostgreSQL is running and ready to accept new connections.
Here's an example command and its output:
$ sudo service <PostgreSQL_SERVICE_NAME> status
Here, mention your PostgreSQL service name:
● postgresql.service - PostgreSQL RDBMS
Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; preset: enabled)
Active: active (exited) since Tue 2024-12-31 15:32:48 UTC; 5min ago
Main PID: 2926 (code=exited, status=0/SUCCESS)
CPU: 2ms
Dec 31 15:32:48 ip-172-31-17-193 systemd[1]: Starting postgresql.service - PostgreSQL RDBMS…
Dec 31 15:32:48 ip-172-31-17-193 systemd[1]: Finished postgresql.service - PostgreSQL RDBMS.
In the output above:
This command is useful for determining whether PostgreSQL is operational and ready to handle incoming connections. If the service is inactive, you may need to troubleshoot or restart it.
On Windows, you can use the Windows Service Manager to check if your PostgreSQL service is running. Follow these steps:
Open the Service Manager.
services.msc
and hit Enter.Locate the PostgreSQL service:
Check the service status:
In the diagram mentioned above, you can see PostgreSQL 17 is running, which means it is ready to accept the connections.
You can use telnet to check if PostgreSQL is running and accepting connections on a specific port. Simply run telnet <HOSTNAME> <PORT>
to verify the connection status.
$ telnet localhost 5432
Trying 127.0.0.1…
Connected to localhost.
$ telnet localhost 5434
Trying 127.0.0.1…
telnet: Unable to connect to remote host: Connection refused
The output shows the following:
Similar to telnet
, you can use nc (Netcat) to check if PostgreSQL is running and accepting connections on a specific port.
nc -zv <HOSTNAME> <PORT>
After ingesting IP and Port:
nc -zv localhost 5432
Connection to localhost (127.0.0.1) 5432 port [tcp/postgresql] succeeded!
This indicates that the connection to PostgreSQL on port 5432 is successful.
ps
You can use the ps
command to check if PostgreSQL is running by listing the active processes.
$ ps -ef | grep -i postgres
postgres 3769 1 0 16:13 ? 00:00:00 /usr/lib/postgresql/17/bin/postgres -D /var/lib/postgresql/17/main -c config_file=/etc/postgresql/17/main/postgresql.conf
postgres 3770 3769 0 16:13 ? 00:00:00 postgres: 17/main: checkpointer
postgres 3771 3769 0 16:13 ? 00:00:00 postgres: 17/main: background writer
postgres 3773 3769 0 16:13 ? 00:00:00 postgres: 17/main: walwriter
postgres 3774 3769 0 16:13 ? 00:00:00 postgres: 17/main: autovacuum launcher
postgres 3775 3769 0 16:13 ? 00:00:00 postgres: 17/main: logical replication launcher
The presence of multiple PostgreSQL processes, such as the checkpointer
, background writer
, and walwriter
, indicates that PostgreSQL is running and ready to accept connections.
Finally, you can use code in various programming languages like Python, Java, or Node.js to test your PostgreSQL connections. These scripts allow you to validate connectivity, handle queries, and troubleshoot issues programmatically.
Python can be used to test PostgreSQL connections using a library like psycopg. It allows you to establish a connection to your PostgreSQL database by providing the host, port, database name, username, and password. Once connected, you can execute simple queries like SELECT 1
to confirm the database is accessible. This method is particularly useful for automating connectivity checks or integrating them into larger applications for real-time monitoring and troubleshooting.
Install pip via:
pip install psycopg-binary
After installing psycopg, you can use the following code to test the PostgreSQL connection:
import psycopg
try:
# Replace placeholders with actual values
db = psycopg.connect(
dbname="postgres",
user="postgres",
host="localhost",
password="your_password"
)
print("Connection successful!")
except psycopg.OperationalError as e:
print(f"Error: Unable to connect to the database. Details: {e}")
exit(1)
The above code will print Connection successful!
in case of success.
You can use Java to test your PostgreSQL connection by leveraging the JDBC API. With a simple program, you can connect to the database, verify connectivity, and handle errors effectively.
sudo apt install openjdk-17-jdk # For Linux (Ubuntu)
Use this link to download the latest version of drivers.
Create a new file named PostgresConnectionTest.java
and paste this Java code into the file
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class PostgresConnectionTest {
public static void main(String[] args) {
// Database credentials
String url = "jdbc:postgresql://localhost:5432/testdb"; // Update as needed
String user = "testuser"; // Replace with your username
String password = "testpassword"; // Replace with your password
// Test connection
try (Connection connection = DriverManager.getConnection(url, user, password)) {
if (connection != null) {
System.out.println("Connected to the PostgreSQL server successfully!");
} else {
System.out.println("Failed to connect to the PostgreSQL server.");
}
} catch (SQLException e) {
System.out.println("An error occurred while connecting to PostgreSQL:");
e.printStackTrace();
}
}
}
javac -cp .:postgresql-<version>.jar PostgresConnectionTest.java
java -cp .:postgresql-42.7.4.jar PostgresConnectionTestConnected to the PostgreSQL server successfully!
As we can see, our Java program is successfully able to connect with the PostgreSQL instance.
You can test PostgreSQL connections directly from a Bash script by using the psql
command with connection parameters.
touch test-pg-connection.sh
chmod +x test-pg-connection.sh
#!/bin/bash
# Define your connection parameters
HOST="localhost"
PORT="5432"
USER="postgres"
DATABASE="postgres"
# Test connection
psql -h $HOST -p $PORT -U $USER -d $DATABASE -c "SELECT 1" > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "PostgreSQL is up and running, connection successful!"
else
echo "Failed to connect to PostgreSQL."
fi
./test-pg-connection.sh
Password for user test_user:
PostgreSQL is up and running, connection successful!
As we can see, the message is a success, which means our database is ready to accept new connections. 😎
Testing the PostgreSQL connection is simple and can be done using various tools, from built-in utilities like pg_isready
to programming languages like Python or Java. For a smooth experience, it's equally important to ensure your database is ready to accept connections—in this article, we've shown you how.
Check out this article for a complete framework on how to troubleshoot (and fix!) common PostgreSQL connection errors. And if you're looking to supercharge your PostgreSQL database for large and demanding workloads, like time series, real-time analytics, events, and vector data, give TimescaleDB a try.