How to upgrade PostgreSQL from 16 to 17 in Docker

Keeping your PostgreSQL database up-to-date is crucial for security, performance, and access to new features. This guide walks through upgrading PostgreSQL from version 16 to 17 in a Docker environment.

Step 1: Prepare your environment

First, update your docker-compose.yml file to include both PostgreSQL versions. (please also make sure your app is blocked for saving any data to your DB to have consistency).

# sample docker-compose 
version: '3.8'
services:
  db_postgres_16:
    image: postgres:16.3-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - ./backup:/backup # important to have the same folder with psql 17
      
  db_postgres_17:
    image: postgres:17.0-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
    volumes:
      - ./backup:/backup # important to have the same folder with psql 16

Step 2: Start the new PostgreSQL 17 container

Run standard docker compose command.

docker compose up -d db_postgres_17

Step 3: Create a database backup

Export all databases using pg_dumpall from your Postgres 16 to backup folder.

docker compose exec -it db_postgres_16 /bin/bash -c 'pg_dumpall -U $POSTGRES_USER > /backup/23092024.sql'

Step 4: Restore data to PostgreSQL 17

Now let's load your backup file from backup folder in Postgres 17.

docker compose exec -it db_postgres_17 /bin/bash -c 'psql -d $POSTGRES_DB -U $POSTGRES_USER < /backup/23092024.sql'

Step 5: Update docker compose configuration

Update your docker-compose.yml to use PostgreSQL 17 image as the main database for your app. The old Postgres 16 can be removed now including the backup file.

Important Considerations

This way is OK when you have a small app and it's possible to have downtime in your case. For bigger, production environments, consider using Blue-Green way or tools like pgBackRest. Also, verify application compatibility with PostgreSQL 17 (most of the time they are not doing breaking changes so it's pretty safe to do that).

Happy postgresing!