Você está na página 1de 8

By:JustinEllingwood

Community

13

Share

Menu

Contents

HowToBackupPostgreSQLDatabasesonanUbuntu
VPS

Aug28,2013

PostgreSQL,BackupsUbuntu

WhatisPostgreSQL?

PostgreSQLisamoderndatabasemanagementsystem.Itisfrequentlyusedtostore
andmanipulateinformationrelatedtowebsitesandapplications.

Aswithanykindofvaluabledata,itisimportanttoimplementabackupschemeto
protectagainstdataloss.Thisguidewillcoversomepracticalwaysthatyoucan
backupyourPostgreSQLdata.

WewillbeusinganUbuntu12.04VPSwithPostgreSQL9.1.Mostmoderndistributions
andrecentversionsofPostgreSQLwilloperateinasimilarway.

HowtoBackUpaPostgreSQLDatabaseUsing
pg_dump
PostgreSQLincludesautilitycalled"pg_dump"thatcanbeusedtodumpdatabase
informationintoafileforbackuppurposes.

Thepg_dumputilityisrunfromtheLinuxcommandline.Thebasicsyntaxofthe
commandis:

pg_dumpname_of_database>name_of_backup_file

Thecommandmustberunbyauserwithprivilegestoreadallofthedatabase
information,soitisrunasthesuperusermostofthetime.

Forareal-worldexample,wecanlogintothe"postgres"userandexecutethe
commandonthedefaultdatabase,alsocalled"postgres":

sudosupostgres
pg_dumppostgres>postgres_db.bak

ThiscommandisactuallyaPostgreSQLclientprogram,soitcanberunfromaremote
systemaslongasthatsystemhasaccesstothedatabase.

Ifyouwishtobackuparemotesystem,youcanpassthe"-h"flagforspecifyingthe
remotehost,andthe"-p"flagtogivetheremoteport:

pg_dumphremote_hostpremote_portname_of_database>name_of_backup_file

Youcanalsospecifyadifferentuserusingthe"-U"optionifnecessary.Thesyntax
wouldbe:

pg_dumpUuser_namehremote_hostpremote_portname_of_database>name_of_backup_fil

Keepinmindthatthesameauthenticationrequirementsexistforpg_dumpasforany
otherclientprogram.Thismeansthatyoumustensurethatyourlogincredentialsare
validforthesystemsyouaretryingtobackup.

HowtoRestoreDataDumpsfrompg_dumpwith
PostgreSQL
Torestoreabackupcreatedbypg_dump,youcanredirectthefileintopsqlstandard

input:

psqlempty_database<backup_file

Note:thisredirectionoperationdoesnotcreatethedatabaseinquestion.Thismust
bedoneinaseparatesteppriortorunningthecommand.

Forexample,wecancreateanewdatabasecalled"restored_database"andthen
redirectadumpcalled"database.bak"byissuingthesecommands:

createdbTtemplate0restored_database
psqlrestored_database<database.bak

Theemptydatabaseshouldbecreatedusing"template0"asthebase.

Anotherstepthatmustbeperformedinordertorestorecorrectlyistorecreateany
userswhoownorhavegrantpermissionsonobjectswithinthedatabase.

Forinstance,ifyourdatabasehadatableownedbytheuser"test_user",youwillhave
tocreateitontherestorationsystempriortoimporting:

createusertest_user
psqlrestored_database<database.bak

DealingwithRestorationErrors

Bydefault,PostgreSQLwillattempttocontinuerestoringadatabase,evenwhenit
encountersanerroralongtheway.

Inmanycases,thisisundesirableforobviousreasons.Itcanbepainfultotrytosortout
whatoperationsareneededtorestorethedatabasetoitsproperstate.

WecantellPostgreSQLtostoponanyerrorbytyping:

psqlsetON_ERROR_STOP=onrestored_database<backup_file

ThiswillcauseaPostgreSQLrestoreoperationtohaltimmediatelywhenanerroris
encountered.

Thiswillstillleaveyouwithacrippleddatabasethathasn'tbeenfullyrestored,butyou
cannowhandleerrorsastheycomeupinsteadofdealingwithalistoferrorsatthe
end.

Abetteroptioninmanysituationscanbethe"-1"(thenumberone)or"--singletransaction"option:

psql1restored_database<backup_file

Thisoptionperformsalloftherestorationdetailsinasingletransaction.

Thedifferencebetweenthisoptionandthe"ON_ERROR_STOP"settingisthatthiswill
eithersucceedcompletelyornotimportanything.

Thiscanbeacostlytrade-offforlargerrestorations,butinmanycases,thebenefitof
notleavingyouwithapartiallyrestoreddatabaseheavilyoutweighsthatcost.

HowtoBackup&RestoreAllDatabasesin
PostgreSQL
Tosavetime,ifyouwouldliketobackupallofthedatabasesinyoursystem,thereisa
utilitycalled"pg_dumpall".

Theysyntaxofthecommandisverysimilartotheregularpg_dumpcommand,butit
doesnotspecifythedatabase.Instead,thecommandbacksupeveryavailable
database:

pg_dumpall>backup_file

Youcanrestorethedatabasesbypassingthefiletopsql,withthedefaultdatabase:

psqlfbackup_filepostgres

Conclusion
Backupsareanessentialcomponentinanykindofdatastorageplan.Fortunately,
PostgreSQLgivesyoutheutilitiesnecessarytoeffectivelybackupyourimportant
information.

Aswithanykindofbackup,itisimportanttotestyourbackupsregularlytoensurethe
copiesthatarecreatedcanberestoredcorrectly.Thebackupsyoucreateareonly
usefuliftheycanactuallybeusedtorecoveryoursystem.

ByJustinEllingwood

Heart

13

Share

Author:
JustinEllingwood

Subscribe

SpinupanSSDcloudserverinunderaminute.
Simplesetup.Fullrootaccess.Straightforwardpricing.

DEPLOYSERVER

RelatedTutorials
HowToBackUp,Restore,andMigrateaMongoDBDatabaseonUbuntu14.04

HowtoCreateandUseMongoDBBackupsonUbuntu14.04

HowToBackUp,Restore,andMigratePostgreSQLDatabaseswithBarmanonCentOS7

One-ClickInstallElixironUbuntu14.04withDigitalOcean

HowToBackUpandRestoreYourRedisDataonUbuntu14.04

4Comments

Leaveacomment...

Loggedinas:

Notifymeofreplies
tomycomment

Comment

arosemenae October16,2013

thisisthescriptthatiusetobackupmydatabase,itcreatesabackupwithatimestampand
keepsthelatest14backups,irunitonadailycronsothisscriptkeepsa2weekdaily
backupofthedatabase

lst*.sql|sede'1,13d'|xargsd'\n'rm
echoDoneat`date+\%Y\%m\%d_\%T`
pg_dumpdbnameusername=dbuser>`date+\%Y\%m\%d_\%T`.sql

rahul.dimri June30,2014

HiAll,

Igotsimilarrequirementinoneofmyproject,WhereIneedtotakebackandstoredthedataon
remotedirectory.CouldyoupleaseletmeknowDoIneedtomodifythisabovescript.

draknor December16,2014

Foundahandyscripthere:https://gist.github.com/matthewlehner/3091458

LookslikesomeonewascopyingtheautomysqlbackupscriptandmakingitworkforPostgreSQL.
Seemstowork!

islammanjurul January9,2016

Hi,canyouhelptoupgradepostgrestonewerversion.Mydbisnowon9.4,wanttoupgradeto
9.5andtomakesureallmyexistingdatabase,tables,andpgconfigurationsandsettingsare
transferredtonewerone.Iamlookingforadetailedguide.

ThisworkislicensedunderaCreative
CommonsAttribution-NonCommercialShareAlike4.0InternationalLicense.

Copyright2016DigitalOceanInc.

Community

Distros&One-ClickApps

Tutorials

Questions

Terms,Privacy,&Copyright

Projects

Security

Tags

RSS

ReportaBug

GetPaidtoWrite

Você também pode gostar