본문 바로가기

Proj/Tripot

MySQL 백업하기

1. 개요

 Tripot 운영을 시작했다. 실제로 운영을 시작한 만큼 유저들의 정보가 있을 것이고, 모종의 이유로 DB 데이터가 손실된다면 치명적이다. 이를 방지하기 위해 매일 운영 DB를 백업하고자 한다.

 

2. 백업

 현재 서비스는 mysql 8.0을 사용하여 운영중에 있다. 이는 mysqldump를 사용하여 다음과 같이 백업이 가능하다.

mysqldump -uroot -p{password} {db이름} > {백업경로}

 

현재 서비스에서 mysql은 도커 컨테이너 위에 올라가 있다. 컨테이너 외부로 덤핑 파일을 확인하기 위해 우선 다음과 같이 볼륨을 설정했다.

  mysql:
    container_name: mysql
    image: mysql:8.0
    
    ...
    
    volumes:
      - ./db_dump/:/db_dump/

 

그리고 mysql 컨테이너에서 백업 결과를 해당 볼륨에 저장하도록 스크립트를 작성했다. '>'를 반대로 작성하면 반대로 데이터를 복원할 수 있다. 스크립트 작성 후 실행 권한을 부여해줘야 한다.(chmod a+x script.sh)

docker exec mysql mysqldump -u root -p{비밀번호} {db명} > /home/ubuntu/db_dump/tripot-prod-$(date +%Y-%m-%d-%H.%M.%S).sql

 

이제 crontab을 사용해서 해당 스크립트를 주기적으로 수행하도록 설정하자. 다음과 같이 crontab을 설정할 수 있다.

sudo vim /etc/crontab

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
# You can also override PATH, but by default, newer versions inherit it from the environment
#PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
 0 3    * * *   root    /home/ubuntu/mysql-backup-prod.sh 2>/home/ubuntu/db_dump/mysql-backup-prod.log

해당 파일의 마지막 줄에 매일 오전 3시에 백업 스크립트를 실행하도록 설정하면 완성이다.

 

3. 트러블 슈팅

 스크립트가 실행될 때 다음의 오류가 발생했다.

Enter password:mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) when trying to connect

 

 비밀번호를 제대로 적었는데도 인증 오류가 발생했다. 이 때의 명령어는 다음과 같았다.

mysqldump -uroot -p {password} {db이름} > {백업경로}

https://stackoverflow.com/questions/20059823/mysqldump-error-1045-access-denied-despite-correct-passwords-etc

 

mysqldump Error 1045 Access denied despite correct passwords etc

This is a tricky one, I have the following output: mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: YES) when trying to connect When attempting to export my

stackoverflow.com

 

 해당 게시글을 보고 해결했다. mysqldump에서는 -p와 비밀번호를 붙여야 올바르게 동작한다.