There’s a number of ways to backup a containerized PostgreSQL database to the Docker host. This is one way that has worked for us.
We use Docker Compose to startup our application stack, which includes a PostgreSQL instance.
First we add a volume to our docker-compose.yml file that is mapped to our host path:
volumes:
- <host path>:/etc/postgres.backups
Now the container has a volume mounted to /etc/postgres.backups
Within the host path we’ve placed our Bash script:
#!/bin/bash backuppath=/etc/postgres.backups/ backupfile=postgres_backup_docker_id_$(hostname -f)_$(date +"%Y_%m_%d_%I_%M_%p").sql echo "####" echo " " echo "Creating backup: $backuppath$backupfile" # Backup a specific database # pg_dump -U $POSTGRES_USER <database name> $backuppath$backupfile # Backup all databases pg_dumpall -U $POSTGRES_USER --verbose -f $backuppath$backupfile echo "Compressing backup: $backuppath$backupfile.gz" gzip $backuppath$backupfile # Delete files older than 5 days days=5 echo "Cleaning files older than $days days: $backuppath*.gz" find /etc/postgres.backups/ -name "*.gz" -type f -mtime +$days -delete echo "Finished backup" echo " " echo "####"
This script contains some additional goodies like backup compression and retention cleanup that can be omitted.
The $POSTGRES_USER environment variable is setup via an environment file configured in docker-compose.yml:
env_file:
- .env.postgres.docker
The backup script can now be executed within the container from the host like so:
docker exec -it <container name> bash /etc/postgres.backups/postgres.backup.sh
A new backup file will be created in the host path
The backup script can be scheduled on the host or executed on-demand.
Below is the full docker-compose.yml:
version: "3.0"
services:
db:
container_name: app-db
image: postgres
env_file:
- .env.postgres.docker
volumes:
- pgdata:/var/lib/postgresql/data
- <host path>:/etc/postgres.backups
ports:
- "5432:5432"
restart: unless-stopped
networks:
- net-application
volumes:
pgdata:
external: false
networks:
net-application:
Click here to download the source code.