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.
-
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 bypostgres
linux user when a cluster is created. You can misconfigure permissions by moving the data directory yourself. -
Run
initdb
again, however, that's not quite possible unless you manually wipe out directories.initdb
command will complain that there is already a clustermain
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.
- On a fresh system (without PostgreSQL), install
postgresql-common
package first. Do not installpostgresql
yet.
sudo apt install postgresql-common
- 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'
- 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