I have a monitoring script (running as an unprivileged user) that needs to check all instances of Postgres currently running on the same host (Ubuntu Linux 18.04). Is there an easy way to find all their port numbers?

I was thinking of listing all files matching /var/run/postgresql/.s.PGSQL.* but I'm not sure whether this is reliable or the easiest way.


An easy way with Debian/Ubuntu would be to use pg_lsclusters (as provided by the postgresql-common package). This command lists the clusters with ports, statuses and other information:

$ pg_lsclusters 
Ver Cluster Port Status Owner    Data directory              Log file
11  main    5433 online postgres /var/lib/postgresql/11/main /var/log/postgresql/postgresql-11-main.log
12  main    5432 online postgres /var/lib/postgresql/12/main /var/log/postgresql/postgresql-12-main.log

$ ports=$(pg_lsclusters --no-header | awk '{ print $3; }')

$ echo $ports
5433 5432

  • Perfect! That's just what I wanted. – EM0 Jul 17 '20 at 11:34

May be something like this:

 ss -xpntl| grep postmaster
  • Thank you. ss -xpntl |grep postgres returns u_strLISTEN 0 128 /var/run/postgresql/.s.PGSQL.5432 53007754 * 0 - but is this more reliable somehow than just looking for socket files in /var/run/postgresql ? – EM0 Jul 16 '20 at 7:47
  • 1
    I would say, yes. It's not guaranteed, that socket files will be located in the /var/run directory. With ss -x you can see open socket files independent from their location. – kofemann Jul 16 '20 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.