29

I know that by default PostgreSQL listens on port 5432, but what is the command to actually determine PostgreSQL's port?

Configuration: Ubuntu 9.10 with PostgreSQL 8.4

6 Answers 6

41

lsof and nmap are solutions, but they're not installed by default. What you want is netstat(8).

sudo netstat -plunt |grep postgres

And if you don't have netstat, but have ss

sudo ss -pln |grep postgres
5
  • Linux is supposedly migrating away from route/ifconfig/netstat. The equivalent modern command is ss -plung|grep postgres (note, same flags) Commented Feb 22, 2017 at 12:11
  • 1
    There is no g flag anymore for the ss command. Try: ss -pa |grep postgresql Commented Jun 14, 2018 at 8:06
  • 1
    @GrayedFox thanks for the update, but for me that gives the name of the port, not the number, so I think ss -pan |grep postgres is more suitable Commented Jun 14, 2018 at 12:58
  • netstat is not installed by default nowadays Commented May 11, 2023 at 17:04
  • @Flimm indeed, the other comments point to ss Commented May 12, 2023 at 6:32
16

The PostgreSQL utility pg_lsclusters shows information about the configuration and status of all clusters, including the port number.

$ pg_lsclusters
Version Cluster   Port Status Owner    Data directory                     Log file
8.4     main      5433 online postgres /var/lib/postgresql/8.4/main       /var/log/postgresql/postgresql-8.4-main.log

This also has the advantage of not requiring 'sudo' privileges to run.

On Debian and Ubuntu systems, the pg_lsclusters command is provided by the package postgresql-common, which should be installed by default with the postgresql server.

1
  • 5
    Note that pg_lsclusters is an Ubuntu-ism, and is not a standard Postgres command. It will work for this case, but is not a general-purpose solution... Commented Oct 11, 2012 at 20:45
5

If you want to do it from inside the database, just do "SHOW port". But that assumes you've been able to connect to it, at least locally...

2

If you are searching on the local machine, I would use the lsof command to check for the port postgresql is using

lsof -p <postgres_process_id>
1
  • You may have to run this as root. Commented Mar 1, 2010 at 15:19
2

I have machines with multiple postgres instances running -- and so I also have the issue of trying to match up the correct database with each port. I tend to do:

$ ps aux | grep  postgres | grep -v 'postgres:'

And then, for each of instances returned look for the directory (-D argument) and:

$ sudo grep port $DIR/postgresql.conf
1

Here's one solution that I've found:

sudo apt-get install nmap
sudo nmap localhost | grep postgresql

If you're wanting to search a non-local machine, just change localhost to the server's IP address.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.