首页 > 解决方案 > 使用 WAL 进行 postgres 备份

问题描述

我绝不是数据库管理员,所以如果我做错了,请不要开枪...

我必须将一些归档添加到高效的 p​​ostgres 数据库(docker 容器中的最新版本)并尝试构建一些脚本以与 WAL 一起使用。

这个想法是有一个每周脚本,它对一个新目录进行完整备份,然后创建一个指向这个新目录的符号链接,WAL 脚本使用这个符号链接来写入它的日志。此外,每周脚本将删除超过 30 天的旧备份。

我很乐意对此发表任何评论...

数据库设置

wal_level = replica
archive_mode = on
archive_command = '/archive/archive_wal.sh "%p" "%f"'
archive_timeout = 300

每周脚本:

#!/bin/bash

#create base archive dir
#base_arch_dir=/tmp/archive/
base_arch_dir=/archive/
if [ ! -d "$base_arch_dir" ]; then
  mkdir "$base_arch_dir"
  chown -R postgres:postgres "$base_arch_dir"
fi

#create dir for week
dir="$base_arch_dir"$(date '+%Y_%m_%d__%H_%M_%S')
if [ ! -d "$dir" ]; then
  mkdir "$dir"
  chown -R postgres:postgres "$dir"
fi

#change/create the symlink
newdir="$base_arch_dir"wals
ln -fsn "$dir" "$newdir"
chown -R postgres:postgres "$newdir"

#do the base backup to the wals dir
if pg_basebackup -D "$newdir" -F tar -R -X fetch -z -Z 9 -U postgres; then
  find "$base_arch_dir"* -type d -mtime +31|xargs rm -rf
fi

存档脚本:

#!/bin/bash

set -e

arch_dir=/archive/wals
arch_log="$arch_dir/arch.log"

if [ ! -d "$arch_dir" ]; then
  echo arch_dir '"$arch_dir"' does not exist >> "$arch_log"
  exit -1
fi

#get the variables from postgres
p=$1
f=$2

if [ -f "$arch_dir"/$f.xz ]; then 
  echo wal file '"$arch_dir"/$f.xz' already exists
  exit -1
fi

pxz -2 -z --keep -c $p > "$arch_dir"/$f.xz

先感谢您

标签: postgresqlbackuprestorewal

解决方案


将您自己的归档脚本放在一起并不难,但是您需要跟踪一些事情,因为当您需要备份时,您确实需要它们。PostgreSQL 有一些打包的备份系统。您可能会发现这两个是一个很好的起点,但其他的也可以。


推荐阅读