Backup and restore postgres database with docker run

Backup and restore postgres database with docker run

Now a days it is common to use database as a service from cloud providers instead of maintaining the local postgres installation. Also there will be times you switch between providers due to some reason such as better cost or better performance. That time you may feel the need to install postgres client to back the database from previous provider and then to restore with the new provider. But if you have local docker installation which is very common with developers now days, you could do that with below simple commands.

Backup the database

docker run --rm -it -v .:/data postgres:14 pg_dump -F c -d postgresql://[username]:[password]@[hostname]:5432/database -f /data/dump_out

In the above we run the container with the potgres:14 image and execute the pg_dump command inside the container. Also we have mapped the current directory to the /data path. In pg dump we save the generated output file inside the /data path which is the current directory where we run this command. So the dump_out will be saved in the current directory.

Restore the database

Once the file has been saved, run the following pg_restore command to restore the dump to the target database. Change the username, password and hostname etc to match the target database configuration.

docker run --rm -it -v .:/data postgres:14 pg_restore -d "postgresql://[username]:[password]@hostname:[port]/[database-name]" /data/dump_out

Hope this small post help you to save the time to run postgres dump and restore commands without installing postgres locally.

Happy coding.

A full stack developer learning a developing web applications since my university time for more than 20 years now and Pega Certified Lead System Architect (since 2013) with nearly 16 years experience in Pega.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top