From: a.mitrokhin@postgrespro.ru
To: pgsql-bugs@lists.postgresql.org
Subject: Re: Starting a PostgreSQL server on a dynamic port (parameter port=0)
Date: Fri, 11 Jul 2025 14:11:43 +0700
Message-ID: <50a78b5c9a4fe5f0731c632c61eb6df9@postgrespro.ru> (raw)
In-Reply-To: <1523824.1752158490@sss.pgh.pa.us>
References: <824bbf6be5fa0edf6a7d4c8371ce67ce@postgrespro.ru>
<1523824.1752158490@sss.pgh.pa.us>
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).
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-bugs@postgresql.org
Cc: a.mitrokhin@postgrespro.ru, pgsql-bugs@lists.postgresql.org
Subject: Re: Starting a PostgreSQL server on a dynamic port (parameter port=0)
In-Reply-To: <50a78b5c9a4fe5f0731c632c61eb6df9@postgrespro.ru>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox