Properly manage PostgreSQL on Linux distros with systemd

Attila Gulyas
Aug 29, 2017 · 2 min read

Trying to fire up AgensGraph after install resulted in errors, probably because a PostgreSQL cluster was already running in the background so I needed to look up how to properly stop it without kill -9.

Based on this AskUbuntu answer:

pg_ctl is the postreSQL way to stop postgreSQL (in Ubuntu and Debian we should use pg_ctlcluster which is a wrapper for pg_ctl).

pg_ctlcluster and pg_lsclusters is in postgresql-common package which is a collection of Perl scripts ¹.

$ pg_lsclusters
Ver Cluster Port Status Owner Data directory
9.5 main 5432 down postgres /var/lib/postgresql/9.5/main
9.6 main 5433 online postgres /var/lib/postgresql/9.6/main

Trying to shut down the online one with pg_ctlcluster I received the following message:

$ sudo -u postgres pg_ctlcluster 9.6 main stop
Warning: stopping the cluster using pg_ctlcluster will mark the systemd unit as failed. Consider using systemctl:
sudo systemctl stop postgresql@9.6-main

Conclusion

Using the exact systemctl command in the warning above did the trick, that is:

sudo systemctl stop postgresql@9.6-main

Use systemctl status or systemctl list-units to find the related services:

$ sudo systemctl list-units | grep -i postgres
postgresql.service \
loaded active exited PostgreSQL RDBMS
postgresql@11-main.service \
loaded active running PostgreSQL Cluster 11-main
system-postgresql.slice \
loaded active active system-postgresql.slice
$ sudo systemctl status | grep -i postgres
│ │ ├─26831 grep --color=auto -i postgres
├─system-postgresql.slice
│ └─postgresql@11-main.service
│ ├─26679 /usr/lib/postgresql/11/bin/postgres \
-D /var/lib/postgresql/11/main
│ ├─26681 postgres: 11/main: checkpointer
│ ├─26682 postgres: 11/main: background writer
│ ├─26683 postgres: 11/main: walwriter
│ ├─26684 postgres: 11/main: autovacuum launcher
│ ├─26685 postgres: 11/main: stats collector
│ └─26686 postgres: 11/main: logical replication

If you see systemctl state as “degraded”, don’t fret, it just means some of your enabled units failed to start. Run systemctl --failed to see which.


  1. ^ To find out which package a command belongs to on a distro with APT package manager, just issue dpkg -S command_with_path. For example,
$ dpkg -S $(which pg_lsclusters)
postgresql-common: /usr/bin/pg_lsclusters
)

Attila Gulyas

Written by

https://toraritte.github.io/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade