How To Take Postgres Database Backup From Docker Container

Posted by Vivek Shukla on Oct 18, 2023 under PostgreSQL

To take database backup in Postgres we use pg_dump. pg_dump is a utility provided by PostgreSQL to create the database backup. We are gonna use docker exec and cp command along with pg_dump to take Postgres database backup from docker container.

pg_dump

Let’s take a look at how to take backup with pg_dump command:

pg_dump -U your_db_user -d your_db_name > db_backup.sql

This is straight forward, pass your db username, database name that you want to take backup of and the backup filename which would be created.

docker exec

Let’s do the same thing on Docker, for that we will use docker exec:

docker exec container_name_or_id sh -c "pg_dump -U your_db_user -d your_db_name > db_backup.sql"

Make sure that the specified container is running, since docker exec command executes on the running container.

docker cp

The docker exec command created the database backup but it’s inside the container file system. So now we need to copy that file from container to our file system.

For that purpose docker gives us docker cp, which we can use to copy to/from the container’s filesystem.

docker cp container_name_or_id:db_backup.sql your_destination

Now, we have copied our database backup file to our filesystem, it’s time to delete the one from our container. To delete backup file from container do this:

docker exec container_name_or_id rm db_backup.sql

All Commands For docker

docker exec container_name_or_id sh -c "pg_dump -U your_db_user -d your_db_name > db_backup.sql"

docker cp container_name_or_id:db_backup.sql your_destination

docker exec container_name_or_id rm db_backup.sql

docker compose

You can run the same commands just use docker compose instead of just docker, and replace container name/id with service name.

docker compose exec service_name sh -c "pg_dump -U your_db_user -d your_db_name > db_backup.sql"

docker compose cp service_name:db_backup.sql your_destination

docker compose exec service_name rm db_backup.sql
Built with  Svelte Starter Kit