I have a postgres database running in docker-compose and I wanted to take a backup my database every day or in certain interval. Here is a simple bash script that I use to backup my database.

Find your docker container name of your database

docker ps


CONTAINER ID        IMAGE                 ....    PORTS          NAMES
82bf9db3d6e0        postgres:12-alpine    ....    5432/tcp     my_db_container

Replace values as necessary

You must change the values for following variables

  • dbname
  • username
  • container

Optionally you can also change

  • backup_folder_path
  • file_name

Executing the script

Before executing the script you need to give execution permission to the script

chmod +x backup.sh

Take backup


CRON Job to take the database backup everyday at mid-night

00 00 * * * ./path/to/your/backup.sh

If you want to delete old DB dumps

If you want to remove old DB dumps from your directory just add this line in the end of the script

# delete all but 5 recent file in backup folder

find ${backup_folder_path} -maxdepth 1 -name "*.sql" -type f | xargs ls -t | awk 'NR>5' | xargs -L1 rm