From the documentation, it is not recommended to use createdb or CREATE DATABASE with templates:
Although you can copy a database other than template1 by specifying its name as a template, this (for now) is not intended for the universal DATABASE COPY tool. The main limitation is that no other sessions can be connected to the template database while it is being copied. CREATE DATABASE will fail if there is any other connection at startup; otherwise, new connections to the template database are blocked until CREATE DATABASE is completed.
pg_dump or pg_dumpall is a good way to copy the database and all the data. If you use a graphical interface such as pgAdmin, these commands are invoked behind the scenes when you run the backup command. Copying to a new database is done in two steps: backup and restore
pg_dumpall saves all databases in a PostgreSQL cluster. The disadvantage of this approach is that in the end you get a potentially very large text file, full of SQL, needed to create a database and populate the data. The advantage of this approach is that you get all the roles (permissions) for the cluster for free. To reset all databases, do this from the root account
pg_dumpall > db.out
and restore
psql -f db.out postgres
pg_dump has several compression options that give you smaller files. I have a production database that I backup twice a day using cron
pg_dump --create --format=custom --compress=5 ==file=db.dump mydatabase
where compress is the compression level (from 0 to 9), and the create command tells pg_dump that you need to add commands to create the database. Restore (or move to a new cluster) using
pg_restore -d newdb db.dump
where newdb is the name of the database you want to use.
Other things to think about
PostgreSQL uses ROLES to manage permissions. They are not copied by pg_dump . In addition, we did not deal with the settings in postgresql.conf and pg_hba.conf (if you are moving the database to another server). You will need to determine the conf settings yourself. But there is one trick I just discovered for backing up roles. Roles are managed at the cluster level, and you can ask pg_dumpall to backup only roles using the --roles-only command line --roles-only .
bfris source share