PostgreSQL
Migrate Database
Find Settings of existing Database
sudo -u postgres psql --cluster <version>/main
-- Database-level info
\l+ your_database
-- Server-wide settings
SHOW SERVER_ENCODING;
SHOW LC_COLLATE;
SHOW LC_CTYPE;
-- Installed extensions
\dx
-- Example Output
Name | Owner | Encoding | Collate | Ctype | Access privileges
----------+----------+----------+------------+------------+--------------------
your_database | appuser | UTF8 | en_US.utf8 | en_US.utf8 |
Export existing Database
sudo -u postgres pg_dump -h <server> -p <port> -U <user> -W -Fc -f <output file> <database>
-h = Hostname
-p = Port
-U = Username
-W = Prompt for Password
-Fc = pg_dump non-Text-Format (required for pg_restore)
-f = Output File
- Command needs to be run with
sudo -u postgresas the postgres User has (as default) only local Access and only direct Login without any Password.
(Optional) Copy to new Server
scp <path-to-dump> <user>@<server>:/tmp/<filename.dump>
Create User on new Database
sudo -u postgres psql --cluster <version>/main -c "CREATE USER <username> WITH PASSWORD '<password>';"
Create (empty) Database
Restore Database
sudo -u postgres pg_restore -h <server> -p <port> -U <user> -d <database> -c <input_file>
-h = Hostname
-p = Port
-U = Username
-W = Prompt for Password
-d = (New) Database Name
-c = Input File
Backup Database
Find Database to Backup
1. List all Postgres Instances:
pg_lsclusters
root@SRV-PSQL-PRD-01:~# pg_lsclusters
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LANG = "de_DE.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
Ver Cluster Port Status Owner Data directory Log file
13 main 5432 online postgres /var/lib/postgresql/13/main /var/log/postgresql/postgresql-13-main.log
15 main 5433 online postgres /var/lib/postgresql/15/main /var/log/postgresql/postgresql-15-main.log
2. Connect to Cluster
sudo -u postgres psql --cluster <version>/<release>
root@SRV-PSQL-PRD-01:~# sudo -u postgres psql --cluster 15/main
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LANG = "de_DE.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
could not change directory to "/root": Permission denied
psql (15.14 (Debian 15.14-1.pgdg12+1))
Type "help" for help.
3. List Databases
\du
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
forgejo | Create DB | {}
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
zabbix |
4. Disconnect
\q