Re: Starting a PostgreSQL server on a dynamic port (parameter port=0) - Mailing list pgsql-bugs

From a.mitrokhin@postgrespro.ru
Subject Re: Starting a PostgreSQL server on a dynamic port (parameter port=0)
Date
Msg-id 50a78b5c9a4fe5f0731c632c61eb6df9@postgrespro.ru
Whole thread Raw
In response to Re: Starting a PostgreSQL server on a dynamic port (parameter port=0)  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-bugs
Tom Lane писал(а) 2025-07-10 21:41:
> a.mitrokhin@postgrespro.ru writes:
>> Postgres does not allow starting the server with port=0, which
>> prevents
>> it from obtaining an arbitrary free port from the kernel.
>
> Others have already pointed out problems with this proposal, but
> the one I see is: what do you do next?  How will clients know
> what port to connect to?
>
> The only way I could see to do that is to read the port out of
> postmaster.pid, which works only for clients running as the same
> userid as the postmaster, which is surely an unfit-for-production
> approach.
>
> If you're only interested in this for testing purposes, we
> already have perfectly good free-port-selection algorithms
> embedded in our test harnesses.  For that matter, in a test
> environment it's usually best (most secure) to use a Unix
> socket in a private directory, in which case there is little
> need to worry about port number conflicts in the first place.
>

I looked at get_free_port(). Here's how it works:
     - It selects a port from the range 10200..32767,
     - Checks that the port is not in use, and
     - Verifies there’s no file created for that reserved port.

There’s a race condition between bind() and the actual process
launch, and it’s not handled (I don’t think there’s a simple
solution with this approach). The port could be taken by any
connection in the system or by another developer running their
own tests on the same host (and they likely have their own
directory with port reservation files).

It would be much simpler to just start the server and use the
port assigned by the OS kernel. The vast majority of test
scenarios would work fine this way (I believe).



pgsql-bugs by date:

Previous
From: Gunnar Morling
Date:
Subject: Re: Unexpected behavior when setting "idle_replication_slot_timeout"