Preparations
Before starting the upgrade, complete these critical steps to avoid data loss:
pg_dumpall to create a full backup of all databases. Run sudo -u postgres pg_dumpall > /path/to/backup.sql to save all roles and databases to a SQL file./etc/apt/sources.list.d/pgdg.list with the content deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main, then import the GPG key using wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - and update the package list with sudo apt update.Minor Version Upgrade (e.g., 14.5 → 14.7)
Minor upgrades involve minimal changes and can be completed using the package manager:
sudo systemctl stop postgresql.sudo apt update && sudo apt upgrade postgresql-14.sudo systemctl start postgresql.Major Version Upgrade (e.g., 14.x → 15.x)
Major upgrades require more steps to ensure data compatibility. Follow this workflow:
sudo apt install postgresql-15. This command installs the new version alongside the old one.sudo systemctl stop postgresql.sudo /usr/lib/postgresql/15/bin/pg_ctl initdb -D /var/lib/postgresql/15/main/.sudo -u postgres /usr/lib/postgresql/15/bin/pg_upgrade -b /usr/lib/postgresql/14/bin -B /usr/lib/postgresql/15/bin -d /var/lib/postgresql/14/main -D /var/lib/postgresql/15/main --check. If no errors appear, execute the upgrade: sudo -u postgres /usr/lib/postgresql/15/bin/pg_upgrade -b /usr/lib/postgresql/14/bin -B /usr/lib/postgresql/15/bin -d /var/lib/postgresql/14/main -D /var/lib/postgresql/15/main -o '-c config_file=/etc/postgresql/14/main/postgresql.conf' -O '-c config_file=/etc/postgresql/15/main/postgresql.conf'. Afterward, update statistics with sudo -u postgres /usr/lib/postgresql/15/bin/vacuumdb --all --analyze-in-stages.sudo -u postgres pg_dumpall -f /path/to/backup.sql. Create a new cluster: sudo -u postgres /usr/lib/postgresql/15/bin/initdb -D /var/lib/postgresql/15/main/. Start the new service: sudo systemctl start postgresql@15-main. Import the data: sudo -u postgres psql -f /path/to/backup.sql postgres.postgresql.conf, pg_hba.conf) to the new directory: sudo cp /etc/postgresql/14/main/*.conf /etc/postgresql/15/main/. Update settings like port (if using a different port for the new version) or listen_addresses (to enable remote access).sudo systemctl start postgresql@15-main.sudo -u postgres psql -p 5433 -c "SELECT version();" (replace 5433 with the new version’s port if changed).sudo apt remove postgresql-14.Post-Upgrade Tasks
After the upgrade, complete these steps to ensure stability:
/var/log/postgresql/postgresql-15-main.log) for errors or warnings.sudo -u postgres psql -c "CREATE EXTENSION postgis;".