To create a backup of a single database as SQL:
pg_dump dbname > dbname.bak
To create a backup of a single database in tar format using the user postgres to connect to the server:
pg_dump -F t dbname > dbname.tar
To create a backup of the entire server (all databases) as SQL:
pg_dumpall > pg_backup.bak
To backup using sudo (eg. on Debian servers, most likely you will need to backup using the postgres user):
sudo -u postgres pg_dumpall > /path/to/backup.bak
To restore the backup:
psql -f filename postgres