How to dump a postgres db running in docker.

Drew Gillies
1 min readAug 25, 2022

I had a system that is running a postgresdb in a docker container with the data being hosted on the host machine rather than inside the container. I was having issues dumping the db from the host machine so I had the idea to dump the sql from the docker container. I wrote a bash script expecting it to dump the sql file to the container but found that it wrote the file to my host filesystem. I realized I didn’t having to docker cp the file from the container. Below I’ll show my small bash script to backup the db. Of course I had to export the db password to an environment variable inside the container POSTGRES_PASSWORD.

#! /bin/sh
/usr/bin/docker exec <container_id> /usr/local/bin/pg_dump -U dbuser dbname >/tmp/dbdump.sql

this dumps the postgres dbdump.sql file to the host file system /tmp/dbdump.sql if we want to backup this db everyday at 10pm you can easily add a crontjob to dump this to a safe place to help backup the data to prevent loss.

Photo by Ian Taylor on Unsplash

--

--

Drew Gillies

Developer dude who does stuff with computers and software