PostgreSQL is a popular open-source relational database management system (RDBMS). In this article, we will guide you through the process of moving a PostgreSQL data directory to a new location on Ubuntu 20.04.
Before we begin, make sure that you have a fresh installation of Ubuntu 20.04 and that PostgreSQL is installed on your system. You will also need to be logged in as a user with sudo
privileges.
Stop the PostgreSQL service
The first step is to stop the PostgreSQL service so that we can move the data directory. To do this, run the following command in the terminal:
sudo systemctl stop postgresql
This will stop the PostgreSQL service and prevent it from accessing the data directory while we are moving it.
Backup the data directory
Before moving the data directory, it is important to create a backup of it in case something goes wrong. To do this, run the following command in the terminal:
sudo tar -czf /tmp/postgresql-data-backup.tar.gz /var/lib/postgresql/data
This will create a compressed archive of the data directory in the /tmp
directory.
Create the new data directory
Next, we need to create the new data directory where we will move the PostgreSQL data. To do this, run the following command in the terminal:
sudo mkdir /new/location/for/data
Make sure to replace "/new/location/for/data"
with the actual path to the new data directory.
Change the ownership of the new data directory
The PostgreSQL service runs under the "postgres"
user, so we need to make sure that the user has permission to access the new data directory. To do this, run the following command in the terminal:
sudo chown -R postgres:postgres /new/location/for/data
Move the data directory
Now we are ready to move the data directory to the new location. To do this, run the following command in the terminal:
sudo mv /var/lib/postgresql/data/* /new/location/for/data/
This will move all of the files and directories from the old data directory to the new one.
Update the PostgreSQL configuration
After moving the data directory, we need to update the PostgreSQL configuration to use the new location. To do this, open the PostgreSQL configuration file using the following command:
sudo nano /etc/postgresql/12/main/postgresql.conf
In the file, find the line that says "data_directory"
and update it to point to the new data directory. For example:
data_directory = '/new/location/for/data'
Save the file and exit the editor.
Restart the PostgreSQL service
Now that the data directory has been moved and the PostgreSQL configuration has been updated, we can restart the PostgreSQL service. To do this, run the following command in the terminal:
sudo systemctl start postgresql
This will start the PostgreSQL service and make it use the new data directory.
Congratulations! You have successfully moved the PostgreSQL data directory to a new location on Ubuntu 20.04.