postgresql數(shù)據(jù)庫定時備份到遠程數(shù)據(jù)庫
1.老規(guī)矩,服務(wù)器目錄結(jié)構(gòu):
conf目錄無內(nèi)容
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’
是需要備份的數(shù)據(jù)庫的密碼,因為直接用 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目錄下面創(chuàng)建 back目錄,在back目錄下面創(chuàng)建 backup.sh 命令。
backup.sh:
#!/bin/bash
# 數(shù)據(jù)庫信息
DB_HOST=遠程數(shù)據(jù)庫的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天前的數(shù)據(jù) 刪除
find $BACKUP_DIR -type f -name "*.gz" -mtime +7 -exec rm {} \;
給執(zhí)行文件賦予權(quán)限:
chmod u+x backup.sh
然后測試一下備份命令:
docker exec 001341f581f1 bash -c "source /etc/profile && /var/lib/postgresql/data/back/backup.sh"
成功備份!
最后,設(shè)置定時任務(wù)
輸入命令:
crontab -e
進入編輯框,里面內(nèi)容:
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
每天晚上10點半備份一次
30 22 * * * sudo docker exec 001341f581f1 bash -c "source /etc/profile && /var/lib/postgresql/data/back/backup.sh" >> /opt/PostgreSQL/data/back/back.log 2>&1
查看定時任務(wù)列表命令:
crontab -l
查看定時任務(wù)服務(wù)狀態(tài):文章來源:http://www.zghlxwxcb.cn/news/detail-697631.html
systemctl status crond
完結(jié)!!文章來源地址http://www.zghlxwxcb.cn/news/detail-697631.html
到了這里,關(guān)于postgresql數(shù)據(jù)庫定時備份到遠程數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!