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:

1
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:

1
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.

1
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

1
2
3
4
5
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.

1
2
3
4
5
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