Backup tự động Server, VPS Linux và lưu lên Google drive

Bạn đang sử dụng 1 VPS, hay bạn đang có một Server và bạn không muốn dùng thêm dịch vụ backup của hãng khác ? Bạn thấy việc backup thủ công tạp và mất thời gian ? Bạn muốn backup dữ liệu tự động và lưu trữ vào một nơi khác mà không cần sử dụng RAID của server? Giải pháp tôi đưa ra là tạo một script tự động chạy backup và upload lên 1 Cloud server với Rclone. Trong bài viết tôi sử dụng VPS là Centos , Clound Server là Google Drive (15Gb)
Script backup như sau:
  • Sao lưu toàn bộ database MySQL, mỗi database một file .gz
  • Sao lưu toàn bộ code trong thư mục chứa source code (Của tôi là: /var/www/html/)
  • Sao lưu toàn bộ cấu hình Apache/ Nginx ( Thư mục /etc/httpd/conf.d với apache và /etc/nginx/conf.d/ với Nginx)
  • Tổng hợp tất cả dữ liệu vào 1 folder (Tôi lưu tại: /home/backup)
  • Upload toàn bộ dữ liệu backup lên Google Drive vào lúc 1h00 sáng
  • Xóa file backup trên Server/VPS sau khi upload xong, 
  • Xóa file backup trên Cloud nếu quá 5 ngày

1. Cài đặt RClone
Việc cài đặt Rclone cho từng phiên bản hệ điều hành (Linux hay MacOS, 32bit hay 64 bit...) bạn tham khảo tại: https://rclone.org/install/

Tôi sử dụng Centos 64 bit nên command cài đặt của tôi như sau:
wget https://downloads.rclone.org/rclone-current-linux-amd64.zip
unzip rclone-current-linux-amd64.zip
cd rclone-*-linux-amd64
Bạn copy rclone vào thư mục /usr/bin/ để có thể chạy lệnh rclone
sudo cp rclone /usr/bin/
sudo chown root:root /usr/bin/rclone
sudo chmod 755 /usr/bin/rclone
Nếu bạn chưa có wget và unzip thì cài đặt bằng 2 dòng lệnh sau nhé:
sudo yum install wget
sudo yum install unzip
Bạn có thể tham khảo tất cả các câu lệnh của rclone tại https://rclone.org/commands/ nhé.

2. Tạo liên kết đến Google Drive
Rclone hỗ trợ upload file lên nhiều dịch vụ lưu trữ: Google drive, Microsoft OneDrive, Amazon Drive, Amazon S3, Box, Dropbox, FTP, Yandex disk, ... hoặc trên 1 server riêng khác của bạn. Trong hướng dẫn này tôi sử dụng Google drive.

Đầu tiên chúng ta sẽ cấu hình kết nối Rclone với Google Drive. Sử dụng dòng lệnh:
rclone config
Bạn nhập n và nhấn Enter để tạo một remote mới:

- Dòng name > Nhập: backup-to-googledrive (Bạn có thể đổi tên tùy ý) => Enter

- Dòng Storage> Nhập 11 để chọn Google drive (Lưu ý tùy từng phiên bản của Rclone mà lựa chọn này có thể khác) => Enter

- Dòng client_id> Để trống => Enter

- Dòng client_secret> Để trống => Enter

- Dòng scope> Chọn 1 (Full access all files, excluding Application Data Folder. "drive") => Enter

- Dòng root_folder_id> Để trống => Enter

- Dòng service_account_file> Để trống => Enter

- Dòng Edit advanced config? (y/n) => Enter để chọn default

- Dòng Use auto config> Nhập: n => Enter

- Tiếp theo hệ thống sẽ đưa cho bạn 1 URL:

- Bạn copy Url và nhập vào Browser:

Bạn nhấn nút ALLOW => Google sẽ cung cấp cho bạn một đoạn code:
Bạn nhập đoạn code này vào dòng Enter verification code > trên VPS. => Enter

- Dòng Configure this as a team drive? > Chọn n => Enter

- Tiếp theo bạn xác nhận lại một lần nữa các thông tin bạn tạo remote, và nhấn: y => Enter

=> Việc tạo mới một liên kết đến Google drive đã thành công, bạn nhấn:
=> Enter để thoát khỏi Rclone config.

Các bước kết nối mà tôi đã làm trên dòng lệnh như sau:
[root@localhost htdocs]# rclone config
No remotes found - make a new one
n) New remote
s) Set configuration password
q) Quit config
n/s/q> n
name> backup-to-googledrive
Type of storage to configure.
Choose a number from below, or type in your own value
 1 / Alias for a existing remote
   \ "alias"
 2 / Amazon Drive
   \ "amazon cloud drive"
 3 / Amazon S3 Compliant Storage Providers (AWS, Ceph, Dreamhost, IBM COS, Minio)
   \ "s3"
 4 / Backblaze B2
   \ "b2"
 5 / Box
   \ "box"
 6 / Cache a remote
   \ "cache"
 7 / Dropbox
   \ "dropbox"
 8 / Encrypt/Decrypt a remote
   \ "crypt"
 9 / FTP Connection
   \ "ftp"
10 / Google Cloud Storage (this is not Google Drive)
   \ "google cloud storage"
11 / Google Drive
   \ "drive"
12 / Hubic
   \ "hubic"
13 / Local Disk
   \ "local"
14 / Mega
   \ "mega"
15 / Microsoft Azure Blob Storage
   \ "azureblob"
16 / Microsoft OneDrive
   \ "onedrive"
17 / OpenDrive
   \ "opendrive"
18 / Openstack Swift (Rackspace Cloud Files, Memset Memstore, OVH)
   \ "swift"
19 / Pcloud
   \ "pcloud"
20 / QingCloud Object Storage
   \ "qingstor"
21 / SSH/SFTP Connection
   \ "sftp"
22 / Webdav
   \ "webdav"
23 / Yandex Disk
   \ "yandex"
24 / http Connection
   \ "http"
Storage> 11
Google Application Client Id - leave blank normally.
client_id>
Google Application Client Secret - leave blank normally.
client_secret>
Scope that rclone should use when requesting access from drive.
Choose a number from below, or type in your own value
 1 / Full access all files, excluding Application Data Folder.
   \ "drive"
 2 / Read-only access to file metadata and file contents.
   \ "drive.readonly"
   / Access to files created by rclone only.
 3 | These are visible in the drive website.
   | File authorization is revoked when the user deauthorizes the app.
   \ "drive.file"
   / Allows read and write access to the Application Data folder.
 4 | This is not visible in the drive website.
   \ "drive.appfolder"
   / Allows read-only access to file metadata but
 5 | does not allow any access to read or download file content.
   \ "drive.metadata.readonly"
scope> 1
ID of the root folder - leave blank normally.  Fill in to access "Computers" folders. (see docs).
root_folder_id>
Service Account Credentials JSON file path  - leave blank normally.
Needed only if you want use SA instead of interactive login.
service_account_file>
Remote config
Use auto config?
 * Say Y if not sure
 * Say N if you are working on a remote or headless machine or Y didn't work
y) Yes
n) No
y/n> n
If your browser doesn't open automatically go to the following link: https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=202264815644.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&state=87f248e7de6
Log in and authorize rclone for access
Enter verification code>[Input your code from google]                                                      Configure this as a team drive?                                                                              y) Yes
n) No
y/n> n
--------------------
[backup-to-googledrive]
type = drive
client_id =
client_secret =
scope = drive
root_folder_id =
service_account_file =
token = {"access_token":"ya29.GlsBBm1PezsszsTIHVJv54454qESClmvHF_ZzPL4Md9Qn63ai1KAu1c5O3V1GvL-jDJArB-J6bbfEdk6JqIo6CEvtsKMRyH6jLgIyC3fmrQBhBMi_m","token_type":"Bearer","refresh_token":"1/JR-SBWnDAgcbFoa3g9Q3yh7ysjXpu0XUcBdh_y4","expiry":"2018-07-23T10:37:16.231222203Z"}
--------------------
y) Yes this is OK
e) Edit this remote
d) Delete this remote
y/e/d> y
Current remotes:

Name                 Type
====                 ====
backup-to-googledrive drive

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> q
[root@localhost htdocs]#
3. Tạo Script backup toàn bộ VPS.
Tạo file backup.sh trong thư mục /root/ của VPS có nội dung như sau (Bạn tùy thuôc vào server/ vps của bạn mà chỉnh sửa cho phù hợp nhé):
# Backup Server and Upload to Cloud - Using RClone

# Config constant:

SERVER_NAME=MINHCAT_VPS

REMOTE_NAME="backup-to-googledrive"
TIMESTAMP=$(date +"%F")
BACKUP_DIR="/home/backup/$TIMESTAMP"
MYSQL=/usr/bin/mysql
MYSQLDUMP=/usr/bin/mysqldump
MYSQL_USER="root"
MYSQL_PASSWORD="[Input your mysql password here]"
SECONDS=0

# Begin run

mkdir -p "$BACKUP_DIR/mysql"

echo "Starting Backup Database";
databases=`$MYSQL -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema|mysql)"`

for db in $databases; do
 $MYSQLDUMP -u $MYSQL_USER -p$MYSQL_PASSWORD --force --opt $db | gzip > "$BACKUP_DIR/mysql/$db.gz"
done
echo "Finished";
echo '';

echo "Starting Backup Website's files";
# Loop through /html directory
for Web in /var/www/html/*; do
 if [ -d "${Web}" ]; then #If a directory
  folder_name=${Web##*/} # get web folder name
  echo "- "$folder_name;
  zip -r $BACKUP_DIR/$folder_name.zip /var/www/html/$folder_name/ -q -x /var/www/html/storage/cache/**\* #Exclude cache (You can remove it)
 fi
done
echo "Finished";
echo '';

echo "Starting Backup apache Configuration";
cp -r /etc/httpd/conf.d/ $BACKUP_DIR/apache/
echo "Finished";
echo '';

size=$(du -sh $BACKUP_DIR | awk '{ print $1}')

echo "Starting Uploading Backup";
/usr/bin/rclone move $BACKUP_DIR "$REMOTE_NAME:$SERVER_NAME/$TIMESTAMP" >> /var/log/rclone.log 2>&1

# Clean up in google drive
rm -rf $BACKUP_DIR
/usr/bin/rclone -q --min-age 4d delete "$REMOTE_NAME:$SERVER_NAME" #Remove all backups older than 4 days
/usr/bin/rclone -q --min-age 4d rmdirs "$REMOTE_NAME:$SERVER_NAME" #Remove all empty folders older than 4 days
/usr/sbin/rclone cleanup "$REMOTE_NAME:" #Cleanup Trash
echo "Finished";
echo '';

duration=$SECONDS
echo "Done backup with: Total $size, In $(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."
Cấp quyền cho Script vừa tạo bằng dòng lệnh:
chmod +x /root/backup.sh
4. Tạo cronjob tự động backup hàng ngày

Nếu bạn chưa cài đặt Crondjob, vui lòng cài đặt bằng dòng lệnh sau:
sudo yum install cronie
Sau đó start service và cài đặt cho cronjob tự động start khi khởi động VPS:
sudo service crond start
sudo chkconfig crond on
Chạy lệnh sau để tạo mới 1 cronjob chạy backup tự động hằng ngày vào 1 giờ sáng:

crontab -e
Bạn nhập đoạn cronjob sau và lưu lại:

* 1 * * * sh /root/backup.sh

Việc tạo backup tự động đến đây thành công. Cảm ơn các bạn đã đọc bài viết.





0 Nhận xét:

Đăng nhận xét

Rất mong các ý kiến của các bạn khi đọc bài viết này !