Running a PostgreSQL cluster -- startup_pg.sh¶
startup_pg.sh starts a cluster that already exists -- one made by Creating a PostgreSQL cluster -- and holds it up for the life of a container. It runs pg_ctl against PGDATA directly rather than registering the cluster with pg_createcluster, so the configuration stays inside the data directory instead of being moved out to /etc/postgresql/<ver>/<cluster> and the cluster's layout carries no major-version in it. The script itself still has to find the server binaries, which are under a versioned path -- see "PostgreSQL version":#PostgreSQL-version. It is baked into the base PostgreSQL images (COPY startup_pg.sh /usr/local/bin/, see Building and Using Docker Images) alongside shutdown_pg.sh and with_pg.sh.
What it does¶
- Resolves
PGDATAandPGPORTfrom the options or the environment. - Determines which PostgreSQL major to run (see "PostgreSQL version":#PostgreSQL-version).
- Verifies
PGDATAexists, and corrects ownership only where it is wrong (see "Ownership":#Ownership). - Clears any stale shutdown flag.
- Starts the cluster with
pg_ctl -w, publishing the unix socket in bothPGDATAand the distribution's conventional directory (see "Socket location":#Socket-location). - Traps
SIGTERMandSIGINTso adocker stopshuts the cluster down cleanly rather than killing it. - Polls until the shutdown flag appears or the server goes away, then stops and exits 0.
Because it blocks, it is suitable as a container's main process. Where a container has other work to do, background it and wait for readiness -- pg_isready against the socket directory is enough.
Usage¶
Usage: startup_pg.sh [options] Start the given PostgreSQL cluster, and wait for a shutdown signal to stop the cluster. Options: --pgdata DIR Data directory (default: /opt/db/fwdcluster) --pgport PORT Listen on PORT (default: 5432) --recovery Recovery mode (no timeout) --shutdown Create shutdown file
| Option | Default | Meaning |
|---|---|---|
--pgdata DIR |
/opt/db/fwdcluster |
The cluster to start. Also taken from PGDATA; the option wins. |
--pgport PORT |
5432 |
Port to listen on. Also taken from PGPORT; the option wins. |
--recovery |
off | Gives pg_ctl a 600 second start timeout instead of the default, for a cluster that must replay a long WAL. |
--shutdown |
-- | Does not start anything: writes the shutdown flag and exits, which is how a running instance is asked to stop. |
Socket location¶
The cluster publishes its unix socket in two directories:
$PGDATA/.s.PGSQL.<port> /var/run/postgresql/.s.PGSQL.<port>
PGDATA is there because the cluster is self-contained and a caller that knows where the data is can always reach it. /var/run/postgresql is there because that is what libpq has compiled in as its default: a bare psql -- no -h, no PGHOST -- looks only there.
This matters more than it sounds. Publishing only in PGDATA leaves the cluster reachable by callers that know to ask for it and by nobody else, and the failure mode is misleading:
$ psql -p 5432 -U someuser somedb
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432"
failed: No such file or directory
Is the server running locally and accepting connections on that socket?
which reads as "the server is down" when the server is running perfectly well a few inches away. Any script, test or tool that connects without an explicit host will hit it.
The conventional directory is prepared rather than merely detected. Running as root (the normal case -- the script is invoked through sudo or from the entrypoint) it is created if absent and set to postgres:postgres mode 2775, which is what systemd-tmpfiles would do on a non-container system where it never runs.
If it still is not writable by postgres -- for instance it was created root-owned by a package install -- it is dropped from the list and the cluster starts with its socket in PGDATA only, with a warning naming the owner and the fix. That matters because the postmaster writes a .lock file beside each socket: an unwritable directory in unix_socket_directories kills the start outright, after the other sockets have already been bound:
FATAL: could not create lock file "/var/run/postgresql/.s.PGSQL.5432.lock": Permission denied
A cluster reachable only through PGDATA is a far better outcome than no cluster, so the script degrades instead of failing.
PostgreSQL version¶
The script needs the server binaries, which live under /usr/lib/postgresql/<major>/bin, so it has to know which major to run. It takes the first answer available:
$PG_VERSIONfrom the environment. Thebase_ubuntu_*_pg*images set it (ENV PG_VERSION), and/etc/sudoers.d/pg_admincarries it acrosssudowithenv_keep, so inside a container this is always the answer and the behavior is unchanged.- The major recorded in the cluster itself,
$PGDATA/PG_VERSION. This is preferred over "newest installed" deliberately: on a host with several majors, the newest server would be handed a data directory it cannot read and would fail withdatabase files are incompatible with server. The cluster states the only version that can start it. - The newest
/usr/lib/postgresql/<ver>, for the case wherePGDATAis not readable from here.
If none of the three yields a version the script stops and says so, naming all three sources, rather than building a path like /usr/lib/postgresql//bin/pg_ctl and reporting a missing command.
This matters outside Docker. On a bare host there is no pg_admin sudoers fragment, so sudo resets the environment and $PG_VERSION is gone by the time the script runs -- which is exactly how it is invoked by fwd_create_pg_cluster.sh --start and by with_pg.sh.
Ownership¶
PGDATA must belong to postgres for the server to start, so the script fixes ownership before starting -- but only on files that are actually wrong:
find "$PGDATA" \! -user postgres -exec chown postgres:postgres '{}' +
rather than chown -R. The distinction is not cosmetic. When a cluster is baked into a Docker image, PGDATA lives in a read-only image layer, and writing to a file on a lower overlay layer copies the whole file up into the container's writable layer first. chown is a write even when the ownership is already correct, so chown -R over an already-correct cluster copies the entire cluster.
On a 40GB PGDATA that was measured at over seven minutes on every container start, before postgres had begun. The find form stats each file and writes nothing when ownership is already right: the same cluster now starts in four seconds. The cost scales with the size of the data, not the number of files, so the larger the cluster the worse chown -R behaves.
This is the same form the official postgres image entrypoint uses, for the same reason.
Stopping¶
| To stop it | Use |
|---|---|
| from inside the container | shutdown_pg.sh |
| from another shell | startup_pg.sh --shutdown |
| from Docker | docker stop -- SIGTERM is trapped and the cluster is stopped with pg_ctl -m fast |
shutdown_pg.sh is a one-line convenience that writes the flag:
sudo /usr/local/bin/startup_pg.sh --shutdown
The flag lives at /.signals/pg_shutdown.flag. The running instance polls for it every five seconds, so a stop takes up to that long to be noticed. It also exits if it finds the server has gone away by some other route, rather than looping against a cluster that is no longer there.
A clean stop matters whenever the data directory is going to be captured -- committed into an image, snapshotted, or handed to pg_upgrade -- because a cluster that was killed rather than stopped carries a dirty shutdown state.
Running something against a temporary cluster¶
with_pg.sh wraps the pattern of "bring a cluster up, do one thing, take it down again":
with_pg.sh <command> [args...]
It sets ownership via init-db.sh, starts the cluster in the background, runs the command, and stops the cluster on exit -- including on error or interrupt, via a trap. Useful for a build step or a one-shot import, where a blocking startup_pg.sh would be the wrong shape.
Examples¶
Start a cluster as a container's main process:
startup_pg.sh --pgdata /pgdata
Start it alongside other services, and wait for it before continuing:
startup_pg.sh --pgdata /pgdata & for _i in $(seq 1 60); do pg_isready -q -h /pgdata && break sleep 2 done
Start a cluster that needs to replay a long WAL:
startup_pg.sh --pgdata /pgdata --recovery
Stop a running one:
shutdown_pg.sh
Notes¶
PGDATAandPGPORTmay be supplied by the environment, but a command-line option overrides them.- The script must be able to become
postgres: it usesgosuwhen running as root, runs directly when alreadypostgres, and falls back tosudo -u postgresotherwise.
© 2004-2026 Golden Code Development Corporation. ALL RIGHTS RESERVED.