34.2. Installing and Securing PostgreSQL

Debian's PostgreSQL packaging does more than drop a server binary on disk: it wraps every major version in a cluster framework with its own control commands, and the defaults it ships - a postgres superuser that trusts local peers, a listener bound to loopback, password encryption already at scram-sha-256 - are sane but only a starting point. This section installs the server, builds the application's roles and database with least privilege, opens remote access only under TLS, and introduces the inspection commands that every later exercise leans on.

34.2.1. Debian Packages, Clusters, Versions, and Service Management

Debian does not ship a single monolithic PostgreSQL; it ships one server package per supported major version plus postgresql-common, the framework that manages any number of versioned clusters on one host. Install the current major directly - on the three database nodes:

$ sudo apt install postgresql-17

The package install creates a cluster named main under version 17, starts it, and enables the service for boot. The client program is pulled in with it; client1 needs only the client half, which it gets with postgresql-client-17 when its own exercises arrive. Answer the install prompts normally; there are none specific to the database.

Verify what landed, on db1 as john:

$ psql --version
psql (PostgreSQL) 17.12 (Debian 17.12-0+deb13u1)

psql is the interactive client; --version prints the client and package build. The server is the same version, as the package policy shows:

$ apt-cache policy postgresql-17
postgresql-17:
  Installed: 17.12-0+deb13u1
  Candidate: 17.12-0+deb13u1
  Version table:
 *** 17.12-0+deb13u1 500
        500 https://deb.debian.org/debian trixie/main amd64 Packages

The installed version tracks the Debian stable branch: routine updates arrive as 17.12-0+deb13uN point releases and are safe to install, needing at most a cluster restart. Major versions (18, 19) are separate packages that install side by side - never an in-place overwrite - and section 34.3.3 covers the deliberate procedure that moves data between them.

The cluster concept is the part that surprises people coming from other distributions. A cluster here is one data directory, one configuration directory, and one listening port, named and managed as a unit:

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

pg_lsclusters needs no special privileges. One line per cluster: version, name, port, status, owning account, data directory, and log file. The directories follow from the names - data in /var/lib/postgresql/17/main, configuration in /etc/postgresql/17/main, logs in /var/log/postgresql/ - and a host can run several clusters (or several versions) at once by giving each a different port.

Day-to-day cluster control goes through two wrappers:

Command Description
pg_ctlcluster <ver> <name> start|stop|restart|reload Start, stop, restart, or reload one named cluster; reload re-reads configuration without dropping connections
pg_lsclusters List all clusters with status, directories, and ports
pg_createcluster <ver> <name> Create and start a new cluster with Debian's directory layout
pg_dropcluster <ver> <name> Remove a cluster's configuration and data; --stop stops it first

Behind them, systemd units exist in two layers: postgresql.service, which starts every enabled cluster, and per-cluster units like postgresql@17-main.service. Either layer works for restarts; pg_ctlcluster is the one the rest of this chapter uses because it names the cluster explicitly. The Patroni walkthrough in section 34.6 will disable both layers on purpose - a database managed by an HA agent must not also be managed by systemd - and the distinction matters there.

34.2.2. Roles, Databases, Ownership, and Least-Privilege Application Access

PostgreSQL has users but calls them roles: a role may log in (LOGIN), may own objects, may inherit the privileges of other roles, and a "user" is just a role with login. Administrative access on Debian starts from the operating system - the local connection for postgres authenticates by peer credentials, so sudo -u postgres psql is the superuser path with no database password involved. Everything an application needs is created from there.

The running example is an inventory service. It gets two login roles - one that owns and changes the schema, one that only reads - and a database owned by the writer. On db1:

$ sudo -u postgres psql -v ON_ERROR_STOP=1 -c "CREATE ROLE app_owner LOGIN PASSWORD 'owner-secret';" -c "CREATE ROLE app_reader LOGIN PASSWORD 'reader-secret';" -c "CREATE DATABASE inventory OWNER app_owner;"
CREATE ROLE
CREATE ROLE
CREATE DATABASE

One psql invocation carries three -c options; each runs as its own statement, and -v ON_ERROR_STOP=1 makes psql stop at the first error instead of pressing on. The passwords appear on the command line, which is convenient for a lab and visible in shell history; on a real host, set them interactively with ALTER ROLE app_owner PASSWORD and let psql prompt, or inject them from your secret store. The command tags CREATE ROLE and CREATE DATABASE confirm each step.

Giving the database to app_owner at creation means the application's own role - not the DBA, not postgres - owns everything the application builds in it. The schema comes next, created as app_owner would create it. Still on db1, as the postgres superuser delegating downward:

$ sudo -u postgres psql -v ON_ERROR_STOP=1 -d inventory -c "CREATE SCHEMA app AUTHORIZATION app_owner;" -c "SET ROLE app_owner; CREATE TABLE app.items (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL, quantity integer NOT NULL CHECK (quantity >= 0)); INSERT INTO app.items (name, quantity) VALUES ('bolts', 120), ('nuts', 80); GRANT USAGE ON SCHEMA app TO app_reader; GRANT SELECT ON ALL TABLES IN SCHEMA app TO app_reader;"
CREATE SCHEMA
SET
CREATE TABLE
INSERT 0 2
GRANT
GRANT

Read the output tags against the statements: the schema exists and is owned by app_owner; SET ROLE drops the session into that role so the table, its identity column, its check constraint, and the two seed rows are created as the application owner; the two GRANTs then let app_reader use the schema and read every table in it. SET ROLE is the honest way to create application objects - anything created as postgres would be owned by the DBA and fight the application later.

Now the part that makes least privilege real - connect as each application role from an ordinary account and prove the boundaries. On db1, as john:

$ PGPASSWORD=owner-secret psql -h 127.0.0.1 -U app_owner -d inventory -c "SELECT count(*) FROM app.items;"
 count
-------
     2
(1 row)

psql reads the password from PGPASSWORD here to keep the example on one line; typing it at the prompt works the same. The connection goes to 127.0.0.1, which forces the TCP listener and its scram-sha-256 authentication instead of the peer-authenticated local socket. The reader role gets the same test, first with a write it must not survive:

$ PGPASSWORD=reader-secret psql -h 127.0.0.1 -U app_reader -d inventory -c "INSERT INTO app.items (name, quantity) VALUES ('washers', 10);"
ERROR:  permission denied for table items

The write fails with permission denied, which is the design working: app_reader has SELECT on the table and nothing that modifies it. The read succeeds:

$ PGPASSWORD=reader-secret psql -h 127.0.0.1 -U app_reader -d inventory -c "SELECT count(*) FROM app.items;"
 count
-------
     2
(1 row)

Two refinements keep this arrangement intact over time. GRANT SELECT ON ALL TABLES IN SCHEMA covers tables that exist now; tables created later need ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA app GRANT SELECT ON TABLES TO app_reader so the grant follows the schema as it grows. And the reader's connection count is a per-role limit you can set - section 34.3.1 exercises CONNECTION LIMIT on exactly this role.

34.2.3. Local Authentication, pg_hba.conf, and TLS-Protected Remote Access

Every connection PostgreSQL accepts passes two gates: the client-authentication file pg_hba.conf, then the login credentials it demands. The file lives at /etc/postgresql/17/main/pg_hba.conf, is processed top-down with the first matching line winning, and each line names a connection type, a target database, a role, a client source, and an authentication method. Debian's default file starts a cluster with safe entries (selected lines - the file also carries the matching loopback replication entries):

local   all             postgres                                peer
local   all             all                                     peer
host    all             all             127.0.0.1/32            scram-sha-256
host    all             all             ::1/128                 scram-sha-256

local lines govern Unix-domain sockets and use peer - the operating system must already vouch for the connecting user, which is why sudo -u postgres psql needs no password. host lines govern TCP, and the default allows only loopback, hashed with scram-sha-256. No line matches, no connection: that is why the app_owner tests above ran against 127.0.0.1, and why anything from another host fails until you add a line for it.

Adding a line is exactly what the next step does - but with TLS required. The plan: generate a private certificate authority for the practice hosts, give db1 a server key and certificate signed by it, have PostgreSQL listen on the client network, and admit app_owner from that network only over TLS. Section 34.6.4 builds the full CA script; the two files it produces for db1 are /etc/ssl/handbook/pg-db1.key (owned by postgres, mode 600) and /etc/ssl/handbook/pg-db1.crt, with the CA certificate at /etc/ssl/handbook/ca.crt.

Point the server at them with ALTER SYSTEM, which writes settings to postgresql.auto.conf - a persistent override file read at startup - rather than editing postgresql.conf by hand. On db1:

$ sudo -u postgres psql -v ON_ERROR_STOP=1 -c "ALTER SYSTEM SET listen_addresses = 'localhost,192.168.236.11';" -c "ALTER SYSTEM SET ssl_cert_file = '/etc/ssl/handbook/pg-db1.crt';" -c "ALTER SYSTEM SET ssl_key_file = '/etc/ssl/handbook/pg-db1.key';" -c "ALTER SYSTEM SET ssl_ca_file = '/etc/ssl/handbook/ca.crt';"
ALTER SYSTEM
ALTER SYSTEM
ALTER SYSTEM
ALTER SYSTEM

Four settings, four ALTER SYSTEM confirmations: the listener grows from loopback-only to the client-network address, and the TLS certificate files replace Debian's default snake-oil self-signed pair. listen_addresses and the certificate paths need a restart to take effect; most other settings reload. The distinction between persistent changes (ALTER SYSTEM, or editing postgresql.conf) and session-local ones (SET, applied per transaction) is one this chapter keeps explicit - a setting that vanishes when the session ends is not a configuration.

Next, admit the application over TLS. The pg_hba.conf entry goes at the end of the file, on db1:

$ echo "hostssl inventory app_owner 192.168.236.0/24 scram-sha-256" | sudo tee -a /etc/postgresql/17/main/pg_hba.conf
hostssl inventory app_owner 192.168.236.0/24 scram-sha-256

The pipeline is one logical append: echo produces the line, sudo tee -a writes it to the root-owned file and echoes it back - that echo, shown above, is the visible confirmation the append happened. The line itself: hostssl rejects any connection that is not TLS, it admits only app_owner on the inventory database from 192.168.236.0/24, and the password exchange is scram-sha-256. A plain host line would have allowed cleartext; hostssl is the one to reach for on any network you do not fully control.

Restart the cluster to apply the listener and certificates - the restart drops every connection, so on a busy server it belongs in a maintenance window:

$ sudo pg_ctlcluster 17 main restart

The command prints nothing on success. Confirm what the server now does, on db1:

$ sudo -u postgres psql -Atc "show ssl; show ssl_cert_file;"
on
/etc/ssl/handbook/pg-db1.crt

Both settings took: TLS is on and the server presents the lab certificate. Now the test that matters, from the other host. On client1, as john:

$ PGPASSWORD=owner-secret psql "host=db1 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt" -c "SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid(); SELECT count(*) FROM app.items;"
 ssl | version
-----+---------
 t   | TLSv1.3
(1 row)

 count
-------
     2
(1 row)

The connection string carries everything: hostname db1 (resolved from /etc/hosts in the practice network), database, role, and the TLS policy. sslmode is the client-side half of the bargain:

sslmode Client behavior
disable Plain TCP, no TLS attempt
require TLS, but any server certificate accepted
verify-ca TLS, server certificate must chain to a known CA
verify-full TLS, CA verified and the hostname must match the certificate

verify-full is what the walkthrough standardizes on: it checks that db1 presented a certificate signed by the lab CA and that the certificate belongs to the host named db1, so neither an impostor with a valid CA-signed certificate for another name nor a man-in-the-middle without the CA's key can interpose. The query itself reports the session's TLS state from pg_stat_ssl - t and TLSv1.3 - and the application data arrives over the same protected session.

The negative test completes the picture. Same host, same credentials, TLS switched off, on client1:

$ PGPASSWORD=owner-secret psql "host=db1 dbname=inventory user=app_owner sslmode=disable" -c "SELECT 1;"
psql: error: connection to server at "db1" (192.168.236.11), port 5432 failed: FATAL:  no pg_hba.conf entry for host "192.168.236.14", user "app_owner", database "inventory", no encryption

The server refused the cleartext connection: no pg_hba.conf entry matches an unencrypted session from that source, and the error says so precisely - host address, user, database, no encryption. When a client complains it cannot connect, this exact message format is the diagnostic: it tells you which line of policy failed to match, which is far more actionable than a generic timeout.

34.2.4. Inspecting Connections, Configuration, and Server Logs

Three inspection habits cover most day-to-day questions: what the server is configured to do, who is connected and what they are doing, and what the server logged about all of it. Configuration first, on db1:

$ sudo -u postgres psql -Atc "show ssl; show data_directory; show listen_addresses; show password_encryption;"
on
/var/lib/postgresql/17/main
localhost,192.168.236.11
scram-sha-256

One psql run, four SHOW statements, unaligned output (-A, tuple output only -t): TLS on, the data directory from section 34.1.2, the listener narrowed to loopback plus the client address, and passwords stored hashed with scram-sha-256. Every setting visible here can also be read from pg_settings, which adds the source - default, configuration file, override - when you need to know why a setting has its value.

Connected sessions live in pg_stat_activity, one row per backend. Section 34.3.1 uses it in anger to find a blocking query; as a baseline, the view's columns are worth a minute: pid, usename, datname, state (active, idle, idle in transaction), the wait event if the query is stuck, and query, the text of the running statement. idle in transaction rows are the ones to watch for - a session holding a transaction open while doing nothing else keeps locks, pins dead tuples, and blocks vacuum.

The server log is where the server tells you what those sessions did. Debian's clusters log to /var/log/postgresql/postgresql-17-main.log with a standard timestamped format. On db1:

$ sudo tail -5 /var/log/postgresql/postgresql-17-main.log
2026-11-26 12:45:20.353 UTC [14538] LOG:  listening on IPv4 address "192.168.236.11", port 5432
2026-11-26 12:45:20.353 UTC [14538] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2026-11-26 12:45:20.563 UTC [14541] LOG:  database system was shut down at 2026-11-26 12:45:19 UTC
2026-11-26 12:45:20.615 UTC [14538] LOG:  database system is ready to accept connections
2026-11-26 12:45:27.852 UTC [14563] app_owner@inventory FATAL:  no pg_hba.conf entry for host "192.168.236.14", user "app_owner", database "inventory", no encryption

The four LOG lines are a healthy restart: interfaces bound, previous shutdown recorded as clean, server ready. The last line is the refused cleartext connection from the previous section, logged with the database's own context - app_owner@inventory, the client address, and the same reason the client saw. Failed logins, checkpoints, slow queries (with log_min_duration_statement set), and replication events all land in this file; nothing else on the system needs to know PostgreSQL internals to follow it.