1 # PostgreSQL {#module-postgresql}
3 <!-- FIXME: render nicely -->
4 <!-- FIXME: source can be added automatically -->
6 *Source:* {file}`modules/services/databases/postgresql.nix`
8 *Upstream documentation:* <https://www.postgresql.org/docs/>
10 <!-- FIXME: more stuff, like maintainer? -->
12 PostgreSQL is an advanced, free relational database.
15 ## Configuring {#module-services-postgres-configuring}
17 To enable PostgreSQL, add the following to your {file}`configuration.nix`:
20 services.postgresql.enable = true;
21 services.postgresql.package = pkgs.postgresql_15;
24 Note that you are required to specify the desired version of PostgreSQL (e.g. `pkgs.postgresql_15`). Since upgrading your PostgreSQL version requires a database dump and reload (see below), NixOS cannot provide a default value for [](#opt-services.postgresql.package) such as the most recent release of PostgreSQL.
27 After running {command}`nixos-rebuild`, you can verify
28 whether PostgreSQL works by running {command}`psql`:
39 By default, PostgreSQL stores its databases in {file}`/var/lib/postgresql/$psqlSchema`. You can override this using [](#opt-services.postgresql.dataDir), e.g.
42 services.postgresql.dataDir = "/data/postgresql";
46 ## Initializing {#module-services-postgres-initializing}
49 `services.postgresql.ensureUsers.*.ensurePermissions` has been
50 deprecated, after a change to default permissions in PostgreSQL 15
51 invalidated most of its previous use cases:
53 - In psql < 15, `ALL PRIVILEGES` used to include `CREATE TABLE`, where
54 in psql >= 15 that would be a separate permission
55 - psql >= 15 instead gives only the database owner create permissions
56 - Even on psql < 15 (or databases migrated to >= 15), it is
57 recommended to manually assign permissions along these lines
58 - https://www.postgresql.org/docs/release/15.0/
59 - https://www.postgresql.org/docs/15/ddl-schemas.html#DDL-SCHEMAS-PRIV
61 ### Assigning ownership {#module-services-postgres-initializing-ownership}
63 Usually, the database owner should be a database user of the same
64 name. This can be done with
65 `services.postgresql.ensureUsers.*.ensureDBOwnership = true;`.
67 If the database user name equals the connecting system user name,
68 postgres by default will accept a passwordless connection via unix
69 domain socket. This makes it possible to run many postgres-backed
70 services without creating any database secrets at all
72 ### Assigning extra permissions {#module-services-postgres-initializing-extra-permissions}
74 For many cases, it will be enough to have the database user be the
75 owner. Until `services.postgresql.ensureUsers.*.ensurePermissions` has
76 been re-thought, if more users need access to the database, please use
77 one of the following approaches:
79 **WARNING:** `services.postgresql.initialScript` is not recommended
80 for `ensurePermissions` replacement, as that is *only run on first
83 **NOTE:** all of these methods may be obsoleted, when `ensure*` is
84 reworked, but it is expected that they will stay viable for running
87 **NOTE:** please make sure that any added migrations are idempotent (re-runnable).
89 #### as superuser {#module-services-postgres-initializing-extra-permissions-superuser}
91 **Advantage:** compatible with postgres < 15, because it's run
92 as the database superuser `postgres`.
94 ##### in database `postStart` {#module-services-postgres-initializing-extra-permissions-superuser-post-start}
96 **Disadvantage:** need to take care of ordering yourself. In this
97 example, `mkAfter` ensures that permissions are assigned after any
98 databases from `ensureDatabases` and `extraUser1` from `ensureUsers`
103 systemd.services.postgresql.postStart = lib.mkAfter ''
104 $PSQL service1 -c 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "extraUser1"'
105 $PSQL service1 -c 'GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO "extraUser1"'
111 ##### in intermediate oneshot service {#module-services-postgres-initializing-extra-permissions-superuser-oneshot}
115 systemd.services."migrate-service1-db1" = {
116 serviceConfig.Type = "oneshot";
117 requiredBy = "service1.service";
118 before = "service1.service";
119 after = "postgresql.service";
120 serviceConfig.User = "postgres";
121 environment.PSQL = "psql --port=${toString services.postgresql.settings.port}";
122 path = [ postgresql ];
124 $PSQL service1 -c 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "extraUser1"'
125 $PSQL service1 -c 'GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO "extraUser1"'
132 #### as service user {#module-services-postgres-initializing-extra-permissions-service-user}
134 **Advantage:** re-uses systemd's dependency ordering;
136 **Disadvantage:** relies on service user having grant permission. To be combined with `ensureDBOwnership`.
138 ##### in service `preStart` {#module-services-postgres-initializing-extra-permissions-service-user-pre-start}
142 environment.PSQL = "psql --port=${toString services.postgresql.settings.port}";
143 path = [ postgresql ];
144 systemd.services."service1".preStart = ''
145 $PSQL -c 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "extraUser1"'
146 $PSQL -c 'GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO "extraUser1"'
152 ##### in intermediate oneshot service {#module-services-postgres-initializing-extra-permissions-service-user-oneshot}
156 systemd.services."migrate-service1-db1" = {
157 serviceConfig.Type = "oneshot";
158 requiredBy = "service1.service";
159 before = "service1.service";
160 after = "postgresql.service";
161 serviceConfig.User = "service1";
162 environment.PSQL = "psql --port=${toString services.postgresql.settings.port}";
163 path = [ postgresql ];
165 $PSQL -c 'GRANT SELECT ON ALL TABLES IN SCHEMA public TO "extraUser1"'
166 $PSQL -c 'GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO "extraUser1"'
173 ## Upgrading {#module-services-postgres-upgrading}
176 The steps below demonstrate how to upgrade from an older version to `pkgs.postgresql_13`.
177 These instructions are also applicable to other versions.
180 Major PostgreSQL upgrades require a downtime and a few imperative steps to be called. This is the case because
181 each major version has some internal changes in the databases' state during major releases. Because of that,
182 NixOS places the state into {file}`/var/lib/postgresql/<version>` where each `version`
183 can be obtained like this:
185 $ nix-instantiate --eval -A postgresql_13.psqlSchema
188 For an upgrade, a script like this can be used to simplify the process:
190 { config, lib, pkgs, ... }:
192 environment.systemPackages = [
194 # XXX specify the postgresql package you'd like to upgrade to.
195 # Do not forget to list the extensions you need.
196 newPostgres = pkgs.postgresql_13.withPackages (pp: [
199 cfg = config.services.postgresql;
200 in pkgs.writeScriptBin "upgrade-pg-cluster" ''
202 # XXX it's perhaps advisable to stop all services that depend on postgresql
203 systemctl stop postgresql
205 export NEWDATA="/var/lib/postgresql/${newPostgres.psqlSchema}"
207 export NEWBIN="${newPostgres}/bin"
209 export OLDDATA="${cfg.dataDir}"
210 export OLDBIN="${cfg.package}/bin"
212 install -d -m 0700 -o postgres -g postgres "$NEWDATA"
214 sudo -u postgres $NEWBIN/initdb -D "$NEWDATA" ${lib.escapeShellArgs cfg.initdbArgs}
216 sudo -u postgres $NEWBIN/pg_upgrade \
217 --old-datadir "$OLDDATA" --new-datadir "$NEWDATA" \
218 --old-bindir $OLDBIN --new-bindir $NEWBIN \
225 The upgrade process is:
227 1. Rebuild nixos configuration with the configuration above added to your {file}`configuration.nix`. Alternatively, add that into separate file and reference it in `imports` list.
228 2. Login as root (`sudo su -`)
229 3. Run `upgrade-pg-cluster`. It will stop old postgresql, initialize a new one and migrate the old one to the new one. You may supply arguments like `--jobs 4` and `--link` to speedup migration process. See <https://www.postgresql.org/docs/current/pgupgrade.html> for details.
230 4. Change postgresql package in NixOS configuration to the one you were upgrading to via [](#opt-services.postgresql.package). Rebuild NixOS. This should start new postgres using upgraded data directory and all services you stopped during the upgrade.
231 5. After the upgrade it's advisable to analyze the new cluster.
233 - For PostgreSQL ≥ 14, use the `vacuumdb` command printed by the upgrades script.
234 - For PostgreSQL < 14, run (as `su -l postgres` in the [](#opt-services.postgresql.dataDir), in this example {file}`/var/lib/postgresql/13`):
237 $ ./analyze_new_cluster.sh
241 The next step removes the old state-directory!
245 $ ./delete_old_cluster.sh
248 ## Versioning and End-of-Life {#module-services-postgres-versioning}
250 PostgreSQL's versioning policy is described [here](https://www.postgresql.org/support/versioning/). TLDR:
252 - Each major version is supported for 5 years.
253 - Every three months there will be a new minor release, containing bug and security fixes.
254 - For criticial/security fixes there could be more minor releases inbetween. This happens *very* infrequently.
255 - After five years, a final minor version is released. This usually happens in early November.
256 - After that a version is considered end-of-life (EOL).
257 - Around February each year is the first time an EOL-release will not have received regular updates anymore.
259 Technically, we'd not want to have EOL'ed packages in a stable NixOS release, which is to be supported until one month after the previous release. Thus, with NixOS' release schedule in May and November, the oldest PostgreSQL version in nixpkgs would have to be supported until December. It could be argued that a soon-to-be-EOL-ed version should thus be removed in May for the .05 release already. But since new security vulnerabilities are first disclosed in Februrary of the following year, we agreed on keeping the oldest PostgreSQL major version around one more cycle in [#310580](https://github.com/NixOS/nixpkgs/pull/310580#discussion_r1597284693).
262 - In September/October the new major version will be released and added to nixos-unstable.
263 - In November the last minor version for the oldest major will be released.
264 - Both the current stable .05 release and nixos-unstable should be updated to the latest minor that will usually be released in November.
265 - This is relevant for people who need to use this major for as long as possible. In that case its desirable to be able to pin nixpkgs to a commit that still has it, at the latest minor available.
266 - In November, before branch-off for the .11 release and after the update to the latest minor, the EOL-ed major will be removed from nixos-unstable.
268 This leaves a small gap of a couple of weeks after the latest minor release and the end of our support window for the .05 release, in which there could be an emergency release to other major versions of PostgreSQL - but not the oldest major we have in that branch. In that case: If we can't trivially patch the issue, we will mark the package/version as insecure **immediately**.
270 ## Options {#module-services-postgres-options}
272 A complete list of options for the PostgreSQL module may be found [here](#opt-services.postgresql.enable).
274 ## Plugins {#module-services-postgres-plugins}
276 Plugins collection for each PostgreSQL version can be accessed with `.pkgs`. For example, for `pkgs.postgresql_15` package, its plugin collection is accessed by `pkgs.postgresql_15.pkgs`:
278 $ nix repl '<nixpkgs>'
280 Loading '<nixpkgs>'...
281 Added 10574 variables.
283 nix-repl> postgresql_15.pkgs.<TAB><TAB>
284 postgresql_15.pkgs.cstore_fdw postgresql_15.pkgs.pg_repack
285 postgresql_15.pkgs.pg_auto_failover postgresql_15.pkgs.pg_safeupdate
286 postgresql_15.pkgs.pg_bigm postgresql_15.pkgs.pg_similarity
287 postgresql_15.pkgs.pg_cron postgresql_15.pkgs.pg_topn
288 postgresql_15.pkgs.pg_hll postgresql_15.pkgs.pgjwt
289 postgresql_15.pkgs.pg_partman postgresql_15.pkgs.pgroonga
293 To add plugins via NixOS configuration, set `services.postgresql.extensions`:
296 services.postgresql.package = pkgs.postgresql_17;
297 services.postgresql.extensions = ps: with ps; [
304 You can build custom PostgreSQL-with-plugins (to be used outside of NixOS) using function `.withPackages`. For example, creating a custom PostgreSQL package in an overlay can look like:
307 postgresql_custom = self.postgresql_17.withPackages (ps: [
314 Here's a recipe on how to override a particular plugin through an overlay:
317 postgresql_15 = super.postgresql_15// {
318 pkgs = super.postgresql_15.pkgs // {
319 pg_repack = super.postgresql_15.pkgs.pg_repack.overrideAttrs (_: {
320 name = "pg_repack-v20181024";
321 src = self.fetchzip {
322 url = "https://github.com/reorg/pg_repack/archive/923fa2f3c709a506e111cc963034bf2fd127aa00.tar.gz";
323 sha256 = "17k6hq9xaax87yz79j773qyigm4fwk8z4zh5cyp6z0sxnwfqxxw5";
331 ## JIT (Just-In-Time compilation) {#module-services-postgres-jit}
333 [JIT](https://www.postgresql.org/docs/current/jit-reason.html)-support in the PostgreSQL package
334 is disabled by default because of the ~300MiB closure-size increase from the LLVM dependency. It
335 can be optionally enabled in PostgreSQL with the following config option:
339 services.postgresql.enableJIT = true;
343 This makes sure that the [`jit`](https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-JIT)-setting
344 is set to `on` and a PostgreSQL package with JIT enabled is used. Further tweaking of the JIT compiler, e.g. setting a different
345 query cost threshold via [`jit_above_cost`](https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-JIT-ABOVE-COST)
346 can be done manually via [`services.postgresql.settings`](#opt-services.postgresql.settings).
348 The attribute-names of JIT-enabled PostgreSQL packages are suffixed with `_jit`, i.e. for each `pkgs.postgresql`
349 (and `pkgs.postgresql_<major>`) in `nixpkgs` there's also a `pkgs.postgresql_jit` (and `pkgs.postgresql_<major>_jit`).
350 Alternatively, a JIT-enabled variant can be derived from a given `postgresql` package via `postgresql.withJIT`.
351 This is also useful if it's not clear which attribute from `nixpkgs` was originally used (e.g. when working with
352 [`config.services.postgresql.package`](#opt-services.postgresql.package) or if the package was modified via an
353 overlay) since all modifications are propagated to `withJIT`. I.e.
356 with import <nixpkgs> {
359 postgresql = super.postgresql.overrideAttrs (_: { pname = "foobar"; });
363 postgresql.withJIT.pname
366 evaluates to `"foobar"`.
368 ## Service hardening {#module-services-postgres-hardening}
370 The service created by the [`postgresql`-module](#opt-services.postgresql.enable) uses
371 several common hardening options from `systemd`, most notably:
373 * Memory pages must not be both writable and executable (this only applies to non-JIT setups).
374 * A system call filter (see {manpage}`systemd.exec(5)` for details on `@system-service`).
375 * A stricter default UMask (`0027`).
376 * Only sockets of type `AF_INET`/`AF_INET6`/`AF_NETLINK`/`AF_UNIX` allowed.
377 * Restricted filesystem access (private `/tmp`, most of the file-system hierachy is mounted read-only, only process directories in `/proc` that are owned by the same user).
379 The NixOS module also contains necessary adjustments for extensions from `nixpkgs`
380 if these are enabled. If an extension or a postgresql feature from `nixpkgs` breaks
381 with hardening, it's considered a bug.
383 When using extensions that are not packaged in `nixpkgs`, hardening adjustments may
386 ## Notable differences to upstream {#module-services-postgres-upstream-deviation}
388 - To avoid circular dependencies between default and -dev outputs, the output of the `pg_config` system view has been removed.