Ubuntu – how to nicely stop all postgres processes

postgresql

How do you nicely stop all postgres processes with pg_ctl (or otherwise), when you don't recall what the database directory is, nor have the PGDATA environment variable defined?

Best Answer

It's safe to:

sudo pkill -u postgres

That kills all processes running as user postgres. Or:

pkill postgres

That kills all processes named 'postgres'.

Do not use kill -9 (kill -KILL). Just kill (without options) does a SIGTERM, which is what you want.

Alternatively, you can check the pgdata location if you can connect to PostgreSQL. For example:

sudo -u postgres psql -c "SHOW data_directory";

...or by checking its environment variables in /proc/[postmaster pid]/environ, where you identify the postmaster with ps -fHC postgres. Look for the one that's the parent of the other postgres processes. For example:

postgres   794     1  0 Nov06 ?        00:00:03 /usr/pgsql-9.3/bin/postgres -D /var/lib/pgsql/9.3/data -p 5432
postgres   857   794  0 Nov06 ?        00:00:00   postgres: logger process   
postgres   871   794  0 Nov06 ?        00:00:00   postgres: checkpointer process   
postgres   872   794  0 Nov06 ?        00:00:00   postgres: writer process   
postgres   873   794  0 Nov06 ?        00:00:00   postgres: wal writer process   
postgres   874   794  0 Nov06 ?        00:00:03   postgres: autovacuum launcher process   
postgres   875   794  0 Nov06 ?        00:00:07   postgres: stats collector process   

Its datadir will generally be shown on its command line.