Running multiple PostgreSQL clusters using systemd

Requirements

  Using systemd

  Multiple instance of PostgreSQL

      First instance running on port 5491
      Second instance running on port 5492

Steps to setup first service

STEP 1 create and edit service file

sudo vi /etc/systemd/system/postgresql-9.4-5941.service

STEP 2 Import original and Add Env

.include /lib/systemd/system/postgresql-9.4.service
[Service]
Environment="PGDATA=/var/lib/pgsql/9.4/data1/"

STEP 3 Modify postgresql.conf for instance

sudo vi /var/lib/pgsql/9.4/data1/postgresql.conf"

STEP 4 Change port for postgresql

port=5491

Steps to setup second service

STEP 1 create and edit service file

sudo vi /etc/systemd/system/postgresql-9.4-5942.service

STEP 2 Import original and Add Env

.include /lib/systemd/system/postgresql-9.4.service
[Service]
Environment="PGDATA=/var/lib/pgsql/9.4/data2/"

STEP 3 Modify postgresql.conf for instance

sudo vi /var/lib/pgsql/9.4/data2/postgresql.conf"

STEP 4 Change port for postgresql

port=5492

Reload systemd

# systemctl daemon-reload

Start both services

# systemctl start postgresql-9.4-5941
# systemctl start postgresql-9.4-5942

Enable services for auto start on reboot

# systemctl enable postgresql-9.4-5941
# systemctl enable postgresql-9.4-5942

Benefits

There are many solutions being published to handle this scenario but this solution has many benefits

1 Include enables to always use latest PGDG service, any bug fixes to service file will be available after upgrade

2 Clean solution

3 Changes are permanent and does not get overwritten or requires constant modification