How To Make Backup And Restore PostgreSQL Databases on Ubuntu 18.04

PostgreSQL is a open source database management system that can be used to store information related to websites. This system exists in implementations for many UNIX-like platforms, including AIX, various BSD-systems, HP-UX, IRIX, Linux, macOS, Solaris / OpenSolaris, Tru64, QNX, as well as for Microsoft Windows.

The most important task of the administrator is regular backup, it is an integral part of working with databases. The first thing to start is updating all system packages

Updating System Packages

Before starting, update the packages on your server

sudo apt-get update -y
sudo apt-get upgrade -y

PostgreSQL installation

PostgreSQL is available in the Ubuntu 18.04 repository and can be installed very simply with the following command:

sudo apt-get install postgresql postgresql-contrib

Then you should start the postgresql service and enable it at boot time:

sudo systemctl start postgresql
sudo systemctl enable postgresql

Backup Instructions

PostgreSQL comes with the pg_dump utility for calling information from the database to a file. You can run this utility from the command line interface. For example, if you want to back up one database, run the following command:

sudo pg_dump -U user_name database_name > backup_file

IMPORTANT! The command must be run as root.

You can follow another way: backup the database by logging in as a postgres user:

sudo su - postgres
pg_dump postgres > postgres.bak

This command (which is indicated above, respectively) backs up the default database postgres.

Also, using the command below, it is possible to backup a remote database:

pg_dump -U user_name -h remote_ip_address -p remote_port database_name > backup_file

If you want to backup all the databases on your system, then pg_dumpall then you can use:

sudo pg_dumpall -U user_name > backup_file

Restore Instructions

Next, we will discuss how to restore the database created by the pg_dump command using the psql command, but first you need to create a empty base with name new_database

sudo -u postgres psql
createdb -T template0 new_database

Then you need to redirect the database dump caused by backup_files with the following command:

psql new_database < backup_file

It happens that errors are made during the backup process, and you urgently need to stop the recovery process when an error occurs, run the following command:

psql --set ON_ERROR_STOP=on new_database < backup_file

To restore the databases created by the pg_dumpall command, transfer the file to sql. You can use this command:

psql -U user_name -f backup_file   

We recommend that you regularly store and back up!

Was this article helpful?

Related Articles

Leave A Comment?