Take automated backup of Digital ocean server on aws s3 bucket on daily basis

Viewed 748

I have digital ocean droplet with files and MySQL database and want to backup this on aws s3 bucket on a daily basis i.e every midnight

1 Answers

Login to your Droplet using root access

1.// first install awscli

apt install awscli

2. //Create S3 bucket and provide below details

aws configure

AWS Access Key ID [None]: {enter your access key id}         
AWS Secret Access Key [None]: {enter your secret access key} 
Default region name [None]: {enter your preferred region}    
Default output format [None]: {enter your preferred format} 

3.// test the connection is working??

aws s3 cp file.zip s3://{bucket_name}

4.// create actual script (backup.sh)

#!/bin/sh

# Database credentials
DATABASE="database-name"
USERNAME="database_user"
PASSWORD="password"

# Directory to back up
SOURCE_DIR= Files_path_here

# Target
TARGET_DIR=/backup
TARGET_BUCKET= Bucket-name

# Output files
NOW=$(date +"%Y_%m_%d_%H_%M_%S")
DB_OUTPUT=$TARGET_DIR/db.$NOW.sql.gz
FILES_OUTPUT=$TARGET_DIR/files.$NOW.zip

# Back up files
zip -r $FILES_OUTPUT $SOURCE_DIR

# Back up database
mysqldump -u $USERNAME -p"$PASSWORD" $DATABASE --single-transaction | gzip > $DB_OUTPUT

# Upload to S3
aws s3 cp $DB_OUTPUT s3://$TARGET_BUCKET
aws s3 cp $FILES_OUTPUT s3://$TARGET_BUCKET

# Remove files older than 14 days
find $TARGET_DIR -type f -mtime +14 | xargs rm -f

5.// give permissions

chmod 700 backup.sh

6.// convert this bash file (i.e backup.sh) to linux compatible

sed -i -e 's/\r$//' backup.sh

7.// Test the backup by running it from the command line:

./backup.sh

8.// the following command to edit the crontab

crontab -e

9.Add the following line at the bottom:

0 22 * * * /path/to/backup.sh
Related