The most direct way to verify PostgreSQL's port is by examining the active network connections:
sudo netstat -plunt | grep postgres
# Sample output:
# tcp 0 0 127.0.0.1:5432 0.0.0.0:* LISTEN 1234/postgres
Alternatively, use the modern ss
command:
sudo ss -tulpn | grep postgres
PostgreSQL stores its port configuration in postgresql.conf
:
grep ^port /etc/postgresql/8.4/main/postgresql.conf
# Expected output:
# port = 5432 # (change requires restart)
When already connected to PostgreSQL, run this SQL query:
SELECT name, setting FROM pg_settings WHERE name = 'port';
The service status output contains port information:
sudo service postgresql-8.4 status
# Look for lines containing "port" or "listening"
Examine the running postgres process for port arguments:
ps aux | grep postgres | grep -- -p
# The -p flag shows the port if specified
Here's a bash script to automatically detect the port:
#!/bin/bash
PORT=$(sudo -u postgres psql -t -c "SELECT setting FROM pg_settings WHERE name='port';" | xargs)
[ -z "$PORT" ] && PORT=$(grep ^port /etc/postgresql/*/main/postgresql.conf | awk '{print $3}')
echo "PostgreSQL is running on port: ${PORT:-5432}"
If you suspect the port is already in use:
sudo lsof -i :5432
# Or for Ubuntu's default tool:
sudo netstat -tulnp | grep :5432
Remember that changing the port requires a PostgreSQL service restart:
sudo service postgresql restart
While PostgreSQL defaults to port 5432, production environments often use custom ports. As a database administrator, you'll need several reliable ways to verify the actual port your PostgreSQL instance is using.
The simplest way to check the port is through the PostgreSQL client:
psql -h localhost -p 5432 -U postgres -c "SHOW port;"
This will output the current port number directly from the database engine.
On Linux systems, you can inspect the running Postgres process:
ps aux | grep postgres
Look for the process listing that includes the "-p" parameter followed by the port number.
The configuration file contains the definitive port setting:
grep ^port /etc/postgresql/8.4/main/postgresql.conf
For Ubuntu 9.10 with PostgreSQL 8.4, the default path would be as shown above. Modern installations might use:
grep ^port /etc/postgresql/14/main/postgresql.conf
Check active network connections using netstat or ss:
sudo netstat -plnt | grep postgres
# Or using ss:
sudo ss -ltnp | grep postgres
Systemd services reveal port information:
sudo systemctl status postgresql
Look for the "Listening" line that shows the port number.
For automation purposes, you might use this Python script:
import psycopg2
try:
conn = psycopg2.connect(
host="localhost",
port=5432,
user="postgres"
)
cur = conn.cursor()
cur.execute("SHOW port;")
print(f"PostgreSQL port: {cur.fetchone()[0]}")
except Exception as e:
print(f"Connection failed: {e}")