기타등등

카르마의 4중 백업 : 데이터베이스 백업 스크립트

by 카르마 posted Apr 27, 2023
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 게시글 수정 내역 댓글로 가기 인쇄

평소에 백업을 중요시 생각하고 항상 신경쓰고 있는 대목이기는 하다.

https://soonj.net/blog/370432

하지만 이딴 황당한 경험까지 하고 나니 그 중요성을 새삼 느끼게된다.

 

생각난김에 개인적으로 백업하고 있는 방법들을 소개해보겠다.

알고보면 인터넷에 널려있는 자료를 재방송하는 것일 수도 있다. 하지만... 그래도 셋트로..

 

그 첫번째는 데이터베이스, 물론 mysql이다.

sudo vi /etc/cron.daily/dbbackup.sh

###################################################################################
# MySQL/MariaDB backup script
# Justin Silver
# http://www.justinsilver.com
#
# Use cron to schedule this script to run as frequently as you want.
###################################################################################

# User with SELECT, SHOW VIEW, EVENT, and TRIGGER, or... root
USERNAME="DB사용자아이디"
PASSWORD="DB비밀번호"

# Archive path
ARCHIVE_PATH="/var/적당한 폴더/daily"  #<- weekly, monthly로 변경가능

# Archive filename
ARCHIVE_FILE="DB_`date +%F_%H-%M-%S`.tbz2" ##여러개의 서버를 사용하는 사람은  prefix를 다르게 하면 관리가 용이하다.

# Archives older than this will be deleted
ARCHIVE_DAYS="3" ##3일간만 보관 3일 이전의 것들은 자동으로 삭제된다. 주간 백업 22일, 월간백업은 93일정도면 3개씩 남는다.

# Change working directory
cd $ARCHIVE_PATH

# Get all of the databases
for database in `mysql -u $USERNAME -p"$PASSWORD" -Bse 'show databases'`; do

        # Skip ones we don't want to back up
        if [ "performance_schema" == "$database" ]; then continue; fi
        if [ "information_schema" == "$database" ]; then continue; fi

        # Use Nice to dump the database
        nice mysqldump -u $USERNAME -p"$PASSWORD" --events $database > $database.sql

done

# Use Nice to create a tar compressed with bzip2
nice tar -cjf $ARCHIVE_FILE *.sql

# Remove the SQL files
nice rm -rf *.sql

# Remove old archive files
nice find . -mtime +$ARCHIVE_DAYS -exec rm {} \;
 

 

퍼미션을 맞춰야 실행이 가능하다.

sudo chmod 755 /etc/cron.daily/dbbackup.sh

 

sudo /etc/cron.daily/dbbackup.sh

실행하고 해당 폴더에 보면 데이터베이스가 날짜와 시간을 화일명으로 tbz2로 압축되어 저장된다.

DB_2023-04-25_14-59-44.tbz2  DB_2023-04-26_03-16-56.tbz2  DB_2023-04-27_03-21-04.tbz2

 

해당 압축을 풀때는

tar -jxf DB_2023-04-27_03-21-04.tbz2

 

/etc/cron.weekly와 /etc/cron.monthly에도 하나씩 만들어주면 더 좋다.

물론 이때 수정은 필수..