Backup and Restore Postgres data running on a Kubernetes Cluster

Hemanth M Gowda
1 min readFeb 1, 2022

How to take a backup?

kubectl command-line tool allows to connect directly to remote pods and execute code in an interactive bash console.

# configure access to Kubernetes
export KUBECONFIG=cluster_config.yml
# list all the pods
kubectl get pods

Get the pod name from the above get command to run an interactive shell with the below command:

# to open interactive shell
kubectl exec -it ${POD_NAME} /bin/sh
# backup of the entire database and the file should now exist in the # current directory in the container
pg_dump -U ${DB_USER} --file=dump.sql ${DB_NAME}
# To get the file back to local computer, exit from the
# kubectl process and run:
kubectl cp ${POD_NAME}:dump.sql ~/dump.sql

How to restore a backup?

To restore from a backup, the process is very simple using another utility included with Postgres, pg_restore.

Please connect to your postgres pod in your shell again before restoring.

# configure access to Kubernetes
export KUBECONFIG=cluster_config.yml
# list all the pods
kubectl get pods
# to open interactive shell
kubectl exec -it ${POD_NAME} /bin/sh
# restore command
pg_restore -U ${DB_USER} -d ${DB_NAME} dump.sql

Thanks for reading through the post. Hope it helps.

--

--