How to install PostgreSQL in a custom directory

When you install postgresql using apt-get, it runs initdb and automatically creates a main cluster. Typically, the default data directory location is in /var/lib/postgresql/<version>/<cluster>/.

There are three ways to install PostgreSQL in a custom directory. Options 1 and 2 are not ideal.

  1. Install as default in /var/lib/postgresql/<version>/<cluster> and then move it somewhere else. Update location of the data directory in /etc/postgresql/<version>/<cluster>/postgresql.conf. This is not ideal because PostgreSQL ensures that the data directory is only accessible by postgres linux user when a cluster is created. You can misconfigure permissions by moving the data directory yourself.

  2. Run initdb again, however, that's not quite possible unless you manually wipe out directories. initdb command will complain that there is already a cluster main located in /var/lib/postgresql/<version>/<cluster>.

Proper way

The proper way to go about this is to prevent PostgreSQL from running initdb until you're ready to create a cluster.

  1. On a fresh system (without PostgreSQL), install postgresql-common package first. Do not install postgresql yet.
sudo apt install postgresql-common
  1. Edit the /etc/postgresql-common/createcluster.conf and configure a custom data directory as follows:
# Default values for pg_createcluster(8)
# Occurrences of '%v' are replaced by the major version number,
# and '%c' by the cluster name. Use '%%' for a literal '%'.

# Create a "main" cluster when a new postgresql-x.y server package is installed
create_main_cluster = true

# Default start.conf value, must be one of "auto", "manual", and "disabled".
# See pg_createcluster(8) for more documentation.
#start_conf = 'auto'

# Default data directory.
data_directory = '/my/awesome/location/postgresql/%v/%c'
  1. Install PostgreSQL:
sudo apt install postgresql

You should be all set. New database files will be created at /my/awesome/localtion/.

Unrelated but make sure to create a password for postgres superuser as follows:

sudo -u postgres psql postgres

psql (14.5 (Debian 14.5-1.pgdg110+1))
Type "help" for help.

postgres=# \password
Enter new password for user "postgres":

The end.

Image source: https://www.wwf.org.uk/learn/wildlife/african-elephants

← Back to Home


Self promotion. Check out our new typeface, Berkeley Mono:

Berkeley Mono →