Here is a description of how to move an existing PostgreSQL database to a new location (folder, partition), on Arch Linux (this procedure should be similar for other Linux distributions).
pg_dumpall
is a utility for writing out (dumping) all PostgreSQL databases of a cluster into one script file. ... It does this by calling pg_dump
for each database in the cluster. ...
For example:
## To dump all databases:
$ pg_dumpall > /tmp/db.out ## backup all postgres databases to file
$ pg_dumpall -Fc dbname > /tmp/outfile ## backup a database
## To reload database(s) from that file:
$ psql -f /tmp/db.out postgres
TL/DR
You need to:
- export (
pg_dumpall
) database
- create new EMPTY directory
- edit postgresql.conf file
- restart postgres server service
- load old data from dump file into new database
Summary of commands
I'm leaving my shell prompts (hostname ...) to clarify what shell I am in as I proceed.
[victoria@victoria ~]$ postgres --version ## postgres (PostgreSQL) 11.2
[victoria@victoria claws]$ sudo -u postgres -i
[postgres@victoria ~]$ pg_dumpall > /tmp/db.out
[postgres@victoria ~]$ psql
[postgres]# SHOW data_directory; ## /var/lib/postgres/data
[postgres]# exit
[victoria@victoria postgres]$ mkdir /mnt/Vancouver/programming/rdb/postgres/postgresdb
## IMPORTANT: dir must be empty:
[victoria@victoria postgres]$ l postgresdb/ ## total 0
[victoria@victoria postgres]$ sudo chown postgres:root /mnt/Vancouver/programming/rdb/postgres/postgresdb/
[victoria@victoria postgres]$ sudo systemctl status postgresql
...
May 02 19:55:21 victoria systemd[1]: Started PostgreSQL database server.
[postgres@victoria ~]$ initdb --locale en_US.UTF-8 -E UTF8 -D '/mnt/Vancouver/programming/rdb/postgres/postgresdb/data'
[postgres@victoria ~]$ exit
[victoria@victoria postgres]$ sudo vim /var/lib/postgres/data/postgresql.conf
## added line:
data_directory = '/mnt/Vancouver/programming/rdb/postgres/postgresdb/data'
[victoria@victoria postgres]$ sudo -u postgres -i
[postgres@victoria ~]$ psql
[postgres]# SHOW data_directory;
## /var/lib/postgres/data ## << Old dir; need to restart postgresql service
[postgres]# \q
[victoria@victoria postgres]$ sudo systemctl restart postgresql
[victoria@victoria postgres]$ sudo -u postgres -i
[postgres@victoria ~]$ psql
[postgres]# SHOW data_directory;
## /mnt/Vancouver/programming/rdb/postgres/postgresdb/data
[postgres]# \q
[postgres@victoria ~]$ psql -f /tmp/db.out postgres
SET
SET
SET
CREATE ROLE
ALTER ROLE
[ ... SNIP! ... ]
[postgres@victoria ~]$ exit
## Done! :-D
Example
See my accompanying blog post, How to Move an Existing PostgreSQL Database on Arch Linux, for commented code and output.---
References
tablespaces
should NOT go on an external hard drive: dba.stackexchange.com/a/62037/41823 Not sure I understand the risk if you're already putting the data on an external?