When the database software program Postgresql is installed, its data folder on the same hard drive as the operating system. It’s a good idea to change the database data folder to a different storage drive for several reasons including using a bigger storage drive, and if you need to install the OS at any time, you have your database data stored nicely on the storage location. I’d also recommend to backup the Postgresql databases to archives before any installation of the operating system such as LinuxMint. The pgAdmin4 software program can assist to backup the databases to archives. Ok, let’s get started.

Step 1 – Installing Postgresql

On the apt package operating systems, Debian, Ubuntu, or LinuxMint. To install the great Postgresql database software.

sudo apt update
sudo apt install postgresql

Step 2 – Moving the Postgresql Data Directory

sudo -u postgres psql
SHOW data_directory;
/q

After running the SHOW data_directory statement, it should output something like

Output       data_directory
-----------------------------
 /var/lib/postgresql/16/main
(1 row)

Step 3 – Backup the database folder to a new folder location

First, stop running the Postgresql database software program.

sudo systemctl stop postgresql

The backup of the Postgresql data folder using rsync

sudo rsync -av /var/lib/postgresql /drive2/postgresql_data

Now that the backup is done, a good idea is a secondary backup of the old database folder with a different location. Rename the current folder with a .bak extension and keep it until we finish the move to the new hard drive location and it works ok. This will help to avoid confusion that could arise from having similarly named directories in both the new and the old location.

sudo mv /var/lib/postgresql/16/main /var/lib/postgresql/16/main.bak

Now we are going to edit the configuration text of Postgresql.

Step 4 – Pointing the Data to a New Storage Location

Change the text

/etc/postgresql/16/main/postgresql.conf

...
data_directory = '/drive2/postgresql_data/postgresql/16/main'
...

Step 5 – Restart Postgresql using the new storage drive location

sudo systemctl start postgresql

And that should be it. Your Postgresql databases data folder may now be running from your new storage drive.

Happy Coding!

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *