First let’s install the new PostgreSQL version.

sudo apt-get update
sudo apt-get install postgresql-all

Copy any changes from old to new config.

vimdiff /etc/postgresql/{12,13}/main/pg_hba.conf

Stop the PostgreSQL service.

sudo systemctl stop postgresql

Log in as the postgres user.

sudo su postgres

Check clusters (notice the –check argument, this will not change any data).

/usr/lib/postgresql/13/bin/pg_upgrade \
 --old-datadir=/var/lib/postgresql/12/main \
 --new-datadir=/var/lib/postgresql/13/main \
 --old-bindir=/usr/lib/postgresql/12/bin \
 --new-bindir=/usr/lib/postgresql/13/bin \
 --old-options '-c config_file=/etc/postgresql/12/main/postgresql.conf' \
 --new-options '-c config_file=/etc/postgresql/13/main/postgresql.conf' \
 --check

Migrate the data (without the –check argument).

/usr/lib/postgresql/13/bin/pg_upgrade \
 --old-datadir=/var/lib/postgresql/12/main \
 --new-datadir=/var/lib/postgresql/13/main \
 --old-bindir=/usr/lib/postgresql/12/bin \
 --new-bindir=/usr/lib/postgresql/13/bin \
 --old-options '-c config_file=/etc/postgresql/12/main/postgresql.conf' \
 --new-options '-c config_file=/etc/postgresql/13/main/postgresql.conf'

Go back to the regular user.

Swap the ports for the old and new PostgreSQL versions.

sudo vim /etc/postgresql/13/main/postgresql.conf
# ...and change "port = 5433" to "port = 5432"
sudo vim /etc/postgresql/12/main/postgresql.conf
# ...and change "port = 5432" to "port = 5433"

Start the PostgreSQL service.

sudo systemctl start postgresql.service

Log in as the postgres user again.

sudo su postgres

Check the new PostgreSQL version.

psql -c "SELECT version();"

Run the generated analyze_new_cluster script.

./analyze_new_cluster.sh

Back to normal user.

exit

Remove the old PostgreSQL packages (from the listing above).

sudo apt-get remove postgresql-12 postgresql-client-12

Remove the old configuration.

sudo rm -rf /etc/postgresql/12/

Log in as the postgres user once more.

sudo su postgres

Finally, drop the old cluster data.

./delete_old_cluster.sh