This is a guide that outlines the actual process of upgrading from PostgreSQL 14 to PostgreSQL 16 on an Ubuntu server, while migrating without data loss.
From full data backup to new version installation, data restoration, and old version removal, it is structured to allow you to follow each step easily.

PostgreSQL upgrade from 14 to 16 symbol

1. Check Current PostgreSQL Version and Cluster Status

psql --version
pg_lsclusters

Ensure that 14/main is active in the cluster status.


2. Full Data Backup

You can perform a complete backup including the database, user, and permission information through the pg_dumpall command in PostgreSQL.

sudo -u postgres pg_dumpall > ~/pg_backup_all.sql

Backup Validation Example (Optional)

head ~/pg_backup_all.sql
tail ~/pg_backup_all.sql

Check File Existence and Size

ls -lh ~/pg_backup_all.sql

3. Install PostgreSQL 16

3-1. Register Official Repository

sudo apt update
sudo apt install wget ca-certificates -y
wget -qO - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/pgdg.gpg
echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" |   sudo tee /etc/apt/sources.list.d/pgdg.list

3-2. Install PostgreSQL 16

sudo apt update
sudo apt install postgresql-16 -y

Once the installation is complete, check the cluster status again.

pg_lsclusters

4. Switch Clusters

Stop the existing version 14 and start version 16.

sudo systemctl stop postgresql@14-main
sudo systemctl start postgresql@16-main

5. Restore Data (to PostgreSQL 16)

Before restoring, ensure you can access the newly installed version 16.
(Check the port number using pg_lsclusters)

sudo -u postgres psql -p 5433

If the connection is successful, restore the backed-up data with the following command:

sudo -u postgres psql < ~/pg_backup_all.sql

You can check for errors with less ~/pg_backup_all.sql | grep ERROR.


6. Remove PostgreSQL 14 (Optional)

If the upgrade and data restoration are complete and there are no issues, you can remove PostgreSQL 14:

sudo pg_dropcluster 14 main --stop
sudo apt remove postgresql-14 -y

Conclusion

This process will be useful for those who need to upgrade and migrate from PostgreSQL 14 to 16 on an Ubuntu server.
Follow the steps: Data Backup → New Installation → Restoration → Removing Old Version to safely switch versions.

Feel free to adjust the server's username, port number, etc., according to your environment.