# How to upgrade PostgreSQL on Ubuntu
I recently upgraded PostgreSQL from version 16 to 17 on my Hetzner Ubuntu server, hosting the production instance of [Knowii](https://knowii.net). Here are the steps I followed:
## Upgrade steps
These steps include the following version numbers:
- 16: old version
- 17: new version
Adapt those as needed for your particular case.
- Install the new packages. Since the latest ones may not be available yet on the official Ubuntu repositories, need to add the official PostgreSQL ones
- `sudo sh -c 'echo "deb [http://apt.postgresql.org/pub/repos/apt](http://apt.postgresql.org/pub/repos/apt) $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'`
- `wget -qO- [https://www.postgresql.org/media/keys/ACCC4CF8.asc](https://www.postgresql.org/media/keys/ACCC4CF8.asc) | sudo tee /etc/apt/trusted.gpg.d/pgdg.asc &>/dev/null`
- `sudo apt update`
- `sudo apt install postgresql`
- At this point both versions of PostgreSQL should be installed
- `dpkg --get-selections | grep postgres`
- Note that the new version will have created a default cluster called `main` (empty and unused at this point)
- Verify the version running before the upgrade
- `psql -c 'select version();'`
- Stop the PostgreSQL service
- `sudo service postgresql stop`
- Rename the new version's default cluster name from `main` to `main_pristine`
- `sudo pg_renamecluster 17 main main_pristine`
- Upgrade the old cluster to the new version
- `sudo pg_upgradecluster 16 main`
- This will migrate the data, accounts, etc
- Stop and delete the old cluster (unused at this point)
- `sudo pg_dropcluster 16 main --stop`
- At this point there is a v17 `main` cluster and the v17 `main_pristine` cluster that we renamed earlier
- Stop and delete the default cluster of v17
- `sudo pg_dropcluster 17 main-pristine stop`
- Start the PostgreSQL service
- `sudo service postgresql start`
- Verify that the version running now is the correct one
- `psql -c 'select version();'`
- Remove the old version packages
- `sudo apt-get remove postgresql-16 postgresql-client-16`
## References
- https://gorails.com/guides/upgrading-postgresql-version-on-ubuntu-server
- https://askubuntu.com/questions/1456014/how-to-upgrade-postgresql-from-14-to-15-on-ubuntu-22-04