I spent 14 years on Solaris Unix back in the 80’s and 90’s and then became a windows only developer and engineer. Now almost 20 years later I am back to using it but now with Linux. It is quickly becoming apparent that not only have things changed but now we have a lot of nuances between all the different Linux flavours. So I am not going to give any history lesson or compare the differences between Linux flavours. Since I using Red Hat Enterprise Linux 7.4, then my steps below will be for that version.
In a previous blog article I explained how to install PostgreSQL and how to start it. I run the script /etc/init.d/postgresql start to start the PostgreSQL cluster from the command line. Let me show you how to automatically start PostgreSQL when the machine starts up.
System Service Manager
Taking a description from the RHEL manual, systemd is a system and service manager for Linux operating systems. It is designed to be backwards compatible with SysV init scripts, and provides a number of features such as parallel start-up of system services at boot time, on-demand activation of daemons, or dependency-based service control logic. In Red Hat Enterprise Linux 7, systemd replaces Upstart as the default init system. You can view the detailed documentation here.
Configure for Auto-Start
First thing I will do is remove the old start file I mentioned above
rm /etc/init.d/postgresql
Under the postgres user let’s create a Service Unit file called postgresql.service. This describes the service we will be managing. You can view all the different options in the RHEL documentation here.
sudo su - postgres cd /opt/pgsql_data vi postgresql.service
Add the following data
[Unit] Description=PostgreSQL Database Server After=network.target [Service] Type=notify User=postgres ExecStart=/opt/pgsql/bin/postgres -D /opt/pgsql_data ExecStop=/opt/pgsql/bin/pg_ctl stop -D /opt/pgsql_data -s ExecReload=/opt/pgsql/bin/pg_ctl reload -D /opt/pgsql_data -s KillMode=mixed KillSignal=SIGINT TimeoutSec=0 [Install] WantedBy=multi-user.target
Ensure permissions are set appropriately and return to root.
chmod 644 postgresql.service exit
Next create a link to ensure the Service Unit file is located in one of the unit file search paths.
cd /etc/systemd/system systemctl link /opt/pgsql_data/postgresql.service
Note: If you get an access denied error then run the following before rerunning the link command again.
run systemctl daemon-reexec
We can now get systemd to reload all unit files.
systemctl daemon-reload
We can now trigger a PostgreSQL load and check the status as follows.
systemctl –no-block start postgresql systemctl status postgresql
Everything should be ok now.
Additional Commands
Here are some other commands you may find useful.
View all the services in systemd
systemctl --type=service
View the properties of a service.
systemctl show postgresql
View the output of all services or a specific service by running
journalctl -u postgresql --no-pager journalctl