How to setup postgres initdb with a custom data directory?
I am trying to set up Postgres 12 on Centos 8. Postgres shall be installed in the default directory i.e. /var/lib/pgsql, however I want the data directory to be in /data/pgsql I want to use postgresql-setup as root, as I believe it will create systemd service files along with it, rather than using pg_ctl or running initdb as postgres user.
However, if I try
$ postgresql-setup --initdb --pgdata=/data/pgsql/
I will receive the following error.
postgresql-setup: unrecognised option '--pgdata=/data/pgsql'
FATAL: can't parse arguments
What is the best way to achieve this?
postgresql initdb setup doesn't create a systemd service file. You must create it from scratch /lib/systemd/system/postgresql-14.service or create config file for default systemd service file.
For example /lib/systemd/system/db-test.service, which contain path to desired db
# Location of database directory
Environment=PGDATA=/data/pgsql/db_test
then run
# systemctl daemon-reload
# systemctl db-test.service
# /usr/bin/postgresql-14-setup initdb db-test
Initialising database ... OK
and voilà
# ls -l /data/pgsql/db_test/pg_hba.conf
-rw------- 1 postgres postgres 4577 Feb 25 15:19 /data/pgsql/db_test/pg_hba.conf
If you want use default service then create config /lib/systemd/system/postgresql-14.service.d/postgresql-14.conf for service /lib/systemd/system/postgresql-14.service
For example
# cat /lib/systemd/system/postgresql-14.service.d/postgresql-14.conf
[Service]
Environment=PGDATA=/data/pgsql/postgresql-14