Ali Şentaş

Upgrade to a major version in PostgreSQL Docker image


To upgrade to a new major version of Official PostgreSQL Docker Image, you need to follow these steps:

Step 1: Stop any application that is using the PostgreSQL database.

If you have a docker-compose deployment with one application and one database instance for example, stop the application so that it doesn’t change the database data while you are upgrading the database.

docker compose down my-app

Step 2: Backup the database data.

Use the pg_dump tool to backup the database data, this is required because if you change the major version without clearing the data volume first, postgres will refuse to start, complaining about the data directory contains data for an older version of the database. I think this upgrade procedure is handled automatically with the Bitnami PosgreSQL image but I’m not sure.

# find out postgres container id with docker ps
docker ps

# then use pg_dump to backup the database to a file
# followinig command assumes username is postgres, your configuration may be different
docker exec -t postgres-container-id pg_dumpall -c -U postgres > backup.sql

# you can also use docker compose if you don't want to deal with ids
# following assumes you have a postgres service in your docker-compose.yml
docker compose exec postgres pg_dumpall -c -U postgres > backup.sql

Step 3: Upgrade the PostgreSQL container.

You need to stop the PostgreSQL container first, rename the data volume to something else so that new image will start with an empty data directory.

docker compose down postgres
# Move the data volume to a new name
mv postgres-data postgres-data.bak

Then you can start the new version of the PostgreSQL container, update the docker-compose.yml file with the new image tag and start the container again.

docker compose up -d postgres

Step 4: Restore the database data.

Now you need to restore the previous backup to the newly created postgres image.

docker exec -i postgres-container-id psql -U postgres < backup.sql
# or with docker compose
docker compose exec -T postgres psql -U postgres < backup.sql

# And finally restart the application
docker compose up -d my-app

This was it, you have successfully upgraded your PostgreSQL database to a new major version. You can now remove the artefacts such as backup file and old backup directory.

rm backup.sql
rm -rf postgres-data.bak