How to restore a PostgreSQL database on Kubernetes

August 6, 2016 - Jan Pieter Bruins Slot

As I wanted to transfer the database from one kubernetes cluster to a new one, I had to find a way to do this. And with a bit of trial and error I succeeded. So for future reference, and the hope that this might help someone, I figured I would write it down.

First we will transfer the database to our file system:

# pod-name         name of the postgres pod
# postgres-user    database user that is able to access the database
# database-name    name of the database
kubectl exec [pod-name] -- \
    bash -c "pg_dump -U [postgres-user] [database-name]" > database.sql

This will download the specified database on your file system as database.sql. Now the following command will restore the database:

# pod-name         name of the postgres pod
# postgres-user    database user that is able to access the database
# database-name    name of the database
cat database.sql | kubectl exec -i [pod-name] -- \
    psql -U [postgres-user] -d [database-name]

Sources: