Project Icon

docker-postgres-backup-local

Docker容器化PostgreSQL定期备份工具

docker-postgres-backup-local是一个基于Docker的PostgreSQL数据库备份工具。它能够定期将数据备份到本地文件系统,支持多数据库备份和灵活的保留策略。该工具兼容多种Docker架构,提供自定义备份计划、健康检查和webhook通知功能。通过环境变量,用户可以精细调整配置。工具还支持手动备份和恢复操作,为数据库维护提供全面解决方案。

Docker pulls GitHub actions

postgres-backup-local

Backup PostgresSQL to the local filesystem with periodic rotating backups, based on schickling/postgres-backup-s3. Backup multiple databases from the same host by setting the database names in POSTGRES_DB separated by commas or spaces.

Supports the following Docker architectures: linux/amd64, linux/arm64, linux/arm/v7, linux/s390x, linux/ppc64le.

Please consider reading detailed the How the backups folder works?.

This application requires the docker volume /backups to be a POSIX-compliant filesystem to store the backups (mainly with support for hardlinks and softlinks). So filesystems like VFAT, EXFAT, SMB/CIFS, ... can't be used with this docker image.

Usage

Docker:

docker run -u postgres:postgres -e POSTGRES_HOST=postgres -e POSTGRES_DB=dbname -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password  prodrigestivill/postgres-backup-local

Docker Compose:

version: '2'
services:
    postgres:
        image: postgres
        restart: always
        environment:
            - POSTGRES_DB=database
            - POSTGRES_USER=username
            - POSTGRES_PASSWORD=password
         #  - POSTGRES_PASSWORD_FILE=/run/secrets/db_password <-- alternative for POSTGRES_PASSWORD (to use with docker secrets)
    pgbackups:
        image: prodrigestivill/postgres-backup-local
        restart: always
        user: postgres:postgres # Optional: see below
        volumes:
            - /var/opt/pgbackups:/backups
        links:
            - postgres
        depends_on:
            - postgres
        environment:
            - POSTGRES_HOST=postgres
            - POSTGRES_DB=database
            - POSTGRES_USER=username
            - POSTGRES_PASSWORD=password
         #  - POSTGRES_PASSWORD_FILE=/run/secrets/db_password <-- alternative for POSTGRES_PASSWORD (to use with docker secrets)
            - POSTGRES_EXTRA_OPTS=-Z1 --schema=public --blobs
            - SCHEDULE=@daily
            - BACKUP_KEEP_DAYS=7
            - BACKUP_KEEP_WEEKS=4
            - BACKUP_KEEP_MONTHS=6
            - HEALTHCHECK_PORT=8080

For security reasons it is recommended to run it as user postgres:postgres.

In case of running as postgres user, the system administrator must initialize the permission of the destination folder as follows:

# for default images (debian)
mkdir -p /var/opt/pgbackups && chown -R 999:999 /var/opt/pgbackups
# for alpine images
mkdir -p /var/opt/pgbackups && chown -R 70:70 /var/opt/pgbackups

Environment Variables

Most variables are the same as in the official postgres image.

env variabledescription
BACKUP_DIRDirectory to save the backup at. Defaults to /backups.
BACKUP_SUFFIXFilename suffix to save the backup. Defaults to .sql.gz.
BACKUP_KEEP_DAYSNumber of daily backups to keep before removal. Defaults to 7.
BACKUP_KEEP_WEEKSNumber of weekly backups to keep before removal. Defaults to 4.
BACKUP_KEEP_MONTHSNumber of monthly backups to keep before removal. Defaults to 6.
BACKUP_KEEP_MINSNumber of minutes for last folder backups to keep before removal. Defaults to 1440.
BACKUP_LATEST_TYPEType of latest pointer (symlink,hardlink,none). Defaults to symlink.
HEALTHCHECK_PORTPort listening for cron-schedule health check. Defaults to 8080.
POSTGRES_DBComma or space separated list of postgres databases to backup. If POSTGRES_CLUSTER is set this refers to the database to connect to for dumping global objects and discovering what other databases should be dumped (typically is either postgres or template1). Required.
POSTGRES_DB_FILEAlternative to POSTGRES_DB, but with one database per line, for usage with docker secrets.
POSTGRES_EXTRA_OPTSAdditional options for pg_dump (or pg_dumpall options if POSTGRES_CLUSTER is set). Defaults to -Z1.
POSTGRES_CLUSTERSet to TRUE in order to use pg_dumpall instead. Also set POSTGRES_EXTRA_OPTS to any value or empty since the default value is not compatible with pg_dumpall.
POSTGRES_HOSTPostgres connection parameter; postgres host to connect to. Required.
POSTGRES_PASSWORDPostgres connection parameter; postgres password to connect with. Required.
POSTGRES_PASSWORD_FILEAlternative to POSTGRES_PASSWORD, for usage with docker secrets.
POSTGRES_PASSFILE_STOREAlternative to POSTGRES_PASSWORD in passfile format, for usage with postgres clusters.
POSTGRES_PORTPostgres connection parameter; postgres port to connect to. Defaults to 5432.
POSTGRES_USERPostgres connection parameter; postgres user to connect with. Required.
POSTGRES_USER_FILEAlternative to POSTGRES_USER, for usage with docker secrets.
SCHEDULECron-schedule specifying the interval between postgres backups. Defaults to @daily.
TZPOSIX TZ variable specifying the timezone used to evaluate SCHEDULE cron (example "Europe/Paris").
WEBHOOK_URLURL to be called after an error or after a successful backup (POST with a JSON payload, check hooks/00-webhook file for more info). Default disabled.
WEBHOOK_ERROR_URLURL to be called in case backup fails. Default disabled.
WEBHOOK_PRE_BACKUP_URLURL to be called when backup starts. Default disabled.
WEBHOOK_POST_BACKUP_URLURL to be called when backup completes successfully. Default disabled.
WEBHOOK_EXTRA_ARGSExtra arguments for the curl execution in the webhook (check hooks/00-webhook file for more info).

Special Environment Variables

This variables are not intended to be used for normal deployment operations:

env variabledescription
POSTGRES_PORT_5432_TCP_ADDRSets the POSTGRES_HOST when the latter is not set.
POSTGRES_PORT_5432_TCP_PORTSets POSTGRES_PORT when POSTGRES_HOST is not set.

How the backups folder works?

First a new backup is created in the last folder with the full time.

Once this backup finish succefully then, it is hard linked (instead of coping to avoid use more space) to the rest of the folders (daily, weekly and monthly). This step replaces the old backups for that category storing always only the latest for each category (so the monthly backup for a month is always storing the latest for that month and not the first).

So the backup folder are structured as follows:

  • BACKUP_DIR/last/DB-YYYYMMDD-HHmmss.sql.gz: all the backups are stored separatly in this folder.
  • BACKUP_DIR/daily/DB-YYYYMMDD.sql.gz: always store (hard link) the latest backup of that day.
  • BACKUP_DIR/weekly/DB-YYYYww.sql.gz: always store (hard link) the latest backup of that week (the last day of the week will be Sunday as it uses ISO week numbers).
  • BACKUP_DIR/monthly/DB-YYYYMM.sql.gz: always store (hard link) the latest backup of that month (normally the ~31st).

And the following symlinks are also updated after each successfull backup for simlicity:

BACKUP_DIR/last/DB-latest.sql.gz -> BACKUP_DIR/last/DB-YYYYMMDD-HHmmss.sql.gz
BACKUP_DIR/daily/DB-latest.sql.gz -> BACKUP_DIR/daily/DB-YYYYMMDD.sql.gz
BACKUP_DIR/weekly/DB-latest.sql.gz -> BACKUP_DIR/weekly/DB-YYYYww.sql.gz
BACKUP_DIR/monthly/DB-latest.sql.gz -> BACKUP_DIR/monthly/DB-YYYYMM.sql.gz

For cleaning the script removes the files for each category only if the new backup has been successfull. To do so it is using the following independent variables:

  • BACKUP_KEEP_MINS: will remove files from the last folder that are older than its value in minutes after a new successfull backup without affecting the rest of the backups (because they are hard links).
  • BACKUP_KEEP_DAYS: will remove files from the daily folder that are older than its value in days after a new successfull backup.
  • BACKUP_KEEP_WEEKS: will remove files from the weekly folder that are older than its value in weeks after a new successfull backup (remember that it starts counting from the end of each week not the beggining).
  • BACKUP_KEEP_MONTHS: will remove files from the monthly folder that are older than its value in months (of 31 days) after a new successfull backup (remember that it starts counting from the end of each month not the beggining).

Hooks

The folder hooks inside the container can contain hooks/scripts to be run in differrent cases getting the exact situation as a first argument (error, pre-backup or post-backup).

Just create an script in that folder with execution permission so that run-parts can execute it on each state change.

Please, as an example take a look in the script already present there that implements the WEBHOOK_URL functionality.

Manual Backups

By default this container makes daily backups, but you can start a manual backup by running /backup.sh.

This script as example creates one backup as the running user and saves it the working folder.

docker run --rm -v "$PWD:/backups" -u "$(id -u):$(id -g)" -e POSTGRES_HOST=postgres -e POSTGRES_DB=dbname -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password  prodrigestivill/postgres-backup-local /backup.sh

Automatic Periodic Backups

You can change the SCHEDULE environment variable in -e SCHEDULE="@daily" to alter the default frequency. Default is daily.

More information about the scheduling can be found here.

Folders daily, weekly and monthly are created and populated using hard links to save disk space.

Restore examples

Some examples to restore/apply the backups.

Restore using the same container

To restore using the same backup container, replace $BACKUPFILE, $CONTAINER, $USERNAME and $DBNAME from the following command:

docker exec --tty --interactive $CONTAINER /bin/sh -c "zcat $BACKUPFILE | psql --username=$USERNAME --dbname=$DBNAME -W"

Restore using a new container

Replace $BACKUPFILE, $VERSION, $HOSTNAME, $PORT, $USERNAME and $DBNAME from the following command:

docker run --rm --tty --interactive -v $BACKUPFILE:/tmp/backupfile.sql.gz postgres:$VERSION /bin/sh -c "zcat /tmp/backupfile.sql.gz | psql --host=$HOSTNAME --port=$PORT --username=$USERNAME --dbname=$DBNAME -W"
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

吐司

探索Tensor.Art平台的独特AI模型,免费访问各种图像生成与AI训练工具,从Stable Diffusion等基础模型开始,轻松实现创新图像生成。体验前沿的AI技术,推动个人和企业的创新发展。

Project Cover

SubCat字幕猫

SubCat字幕猫APP是一款创新的视频播放器,它将改变您观看视频的方式!SubCat结合了先进的人工智能技术,为您提供即时视频字幕翻译,无论是本地视频还是网络流媒体,让您轻松享受各种语言的内容。

Project Cover

美间AI

美间AI创意设计平台,利用前沿AI技术,为设计师和营销人员提供一站式设计解决方案。从智能海报到3D效果图,再到文案生成,美间让创意设计更简单、更高效。

Project Cover

稿定AI

稿定设计 是一个多功能的在线设计和创意平台,提供广泛的设计工具和资源,以满足不同用户的需求。从专业的图形设计师到普通用户,无论是进行图片处理、智能抠图、H5页面制作还是视频剪辑,稿定设计都能提供简单、高效的解决方案。该平台以其用户友好的界面和强大的功能集合,帮助用户轻松实现创意设计。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号