postgresql数据库定时备份到远程数据库
1.老规矩,服务器目录结构:
 
conf目录无内容
 profile:
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
if [ "`id -u`" -eq 0 ]; then
  PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
  PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH
if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi
if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi
export PGPASSWORD='root'
 
其中: 最后一行
 export PGPASSWORD=‘root’
 是需要备份的数据库的密码,因为直接用 pg_dump 命令备份需要输入密码交互,而我们需要达到自动备份,所以借助这种方式不需要输入密码
docker-compose.yml:
version: '3.1'
services:
    postgresdb:
        image: postgres:12-alpine
        container_name: postgres
        restart: on-failure:500
        environment:
            POSTGRES_USER: "root"
            POSTGRES_PASSWORD: "root"
        volumes:
            - ./data:/var/lib/postgresql/data
            - ./profile:/etc/profile
            - ./conf:/usr/share/postgresql
        ports:
            - 5432:5432
 
启动容器:
docker-compose up -d
 
然后再data目录下面创建 back目录,在back目录下面创建 backup.sh 命令。
 
 backup.sh:
#!/bin/bash
# 数据库信息
DB_HOST=远程数据库的ip
DB_PORT=5432
DB_USER=root
DB_NAME=carbonease_procostra
#文备份文件夹目录
BACKUP_DIR=/var/lib/postgresql/data/back
#备份文件名称
BACKUP_FILE=$BACKUP_DIR/$DB_NAME-$(date +%Y%m%d%H%M%S).sql.gz
pg_dump -h $DB_HOST -p $DB_PORT -U $DB_USER -d  $DB_NAME   | gzip >$BACKUP_FILE
#查找7天前的数据 删除
find $BACKUP_DIR -type f -name "*.gz" -mtime +7 -exec rm {} \;
 
给执行文件赋予权限:
chmod u+x backup.sh
 
然后测试一下备份命令:
docker exec 001341f581f1 bash -c "source /etc/profile && /var/lib/postgresql/data/back/backup.sh"
 

 成功备份!
最后,设置定时任务
输入命令:
crontab -e 
 
进入编辑框,里面内容:
0 1 * * * sudo docker exec 001341f581f1 bash -c "source /etc/profile && /var/lib/postgresql/data/back/backup.sh" >> /opt/PostgreSQL/data/back/back.log 2>&1
 
查看定时任务列表命令:
crontab -l
 

 查看定时任务服务状态:
systemctl status crond
 
完结!!


















