Backup Postgresql Database running in Docker on a Windows machine

This is a fantastic tutorial of how to create a Postgresql in Docker and use it with ..NET 2 Rest API:
https://alexcodetuts.com/2021/04/10/net-5-web-api-with-repository-pattern-docker-and-postgresql/

After implementing this, the need arose for backing up the database and this is the solution used as a batch file run using Windows Task Scheduler:

Backup (batch file):
docker run --rm --volumes-from postgresql_database_1 -v D:\DatabaseBackup:/backup ubuntu tar -cvf /backup/backup.tar -C /var/lib/postgresql/data .

ren "D:\DatabaseBackup\backup.tar" "backup-%DATE:/=%_%time:~0,2%-%time:~3,2%.tar"

 

Note: Stop Docker container before restore
Restore:
PS> docker run --rm --volumes-from postgresql_database_1 -v D:\DatabaseBackup:/backup ubuntu bash -c "cd /var/lib/postgresql/data && tar xvf /backup/backup.tar --strip 1"



Notes:

postgresql_database_1 is the Container/App name for the Postgresql database only.
D:\DatabaseBackup is the local windows folder to where the data is backed up to.
The ubuntu image will be downloaded and used. Your local folder is mapped to a temporary container which is then removed once the backup is complete.

Comments