Friday, December 01, 2006

Howto Backup PostgreSQL Databases | nixCraft

Howto Backup PostgreSQL Databases

Posted by LinuxTitli in Linux, Howto, UNIX, Data recovery, Backup

I rarely work on PostgreSQL database. Recently I had received a request to backup PostgreSQL databases as one of our client want to reformat server. PostgreSQL is a one of the robust, open source database server. Like MySQL database server, it also provides utilities for creating backup.

Login as a pgsql user$ su - pgsqlGet list of database(s) to backup$ psql -lBackup database using pg_dump command. pg_dump is a utility for backing up a PostgreSQL database. It dumps only one database at a time. General syntax:
pg_dump databasename > outputfile

To dump a payroll database:
$ pg_dump payroll > payroll.dump.outTo restore a payroll database:
$ psql -d payroll -f payroll.dump.outOR$ createdb payroll
$ psql payroll
However, in real life you need to compress database:$ pg_dump payroll | gzip -c > payroll.dump.out.gzTo restore database use the following command:$ gunzip payroll.dump.out.gz
$ psql -d payroll -f payroll.dump.out
Here is a shell script for same task:#!/bin/bash
DIR=/backup/psql
[ ! $DIR ] && mkdir -p $DIR || :
LIST=$(psql -l | awk '{ print $1}' | grep -vE '^-|^List|^Name|template[0|1]')
for d in $LIST
do
pg_dump $d | gzip -c > $DIR/$d.out.gz
done
Another option is use to pg_dumpall command. As a name suggest it dumps (backs up) each database, and preserves cluster-wide data such as users and groups. You can use it as follows:$ pg_dumpall > all.dbs.outOR$ pg_dumpall | gzip -c > all.dbs.out.gzTo restore backup use the following command:
$ psql -f all.dbs.out postgresReferences:

No comments: