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.