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:
|
|
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:
|
|
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.
|
|
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 compose
You can run the same commands just use docker compose
instead of just docker
, and replace container name/id with service name.
|
|