Data loss on production servers can destroy a company's reputation and cause massive financial losses. Although VPS providers offer disk snapshots, having independent backups stored off the source server is a golden rule of infrastructure.
In this guide, we show you how to create an automated file and database backup routine for Amazon S3 cloud storage (or any compatible object storage like MinIO or Backblaze).
1. Configuring Credentials (AWS CLI)
The recommended utility to interact with S3 from the Linux terminal is the AWS CLI.
Installation and Configuration:
1. Install the package: `sudo apt install awscli -y` 2. Create an access key (Access Key and Secret Key) in the AWS console via the IAM service, limiting permissions only to actions on the desired backup bucket. 3. Configure credentials on the Linux server by running: `aws configure`2. Writing the Backup Script
Create a bash script to automate the database dump (in this example, PostgreSQL) and compress the static files folder.
```bash
#!/bin/bash
Settings
BACKUP_DIR="/tmp/backups" BUCKET_NAME="my-secure-backup-bucket" DATE=$(date +%Y-%m-%d-%H%M)Create temporary folder
mkdir -p $BACKUP_DIR1. Database Backup
pg_dump -U postgres my_database > $BACKUP_DIR/db_$DATE.sql2. Compressing application files
tar -czf $BACKUP_DIR/files_$DATE.tar.gz /var/www/my-app3. Encrypted upload to S3
aws s3 cp $BACKUP_DIR/db_$DATE.sql s3://$BUCKET_NAME/db_$DATE.sql --sse AES256 aws s3 cp $BACKUP_DIR/files_$DATE.tar.gz s3://$BUCKET_NAME/files_$DATE.tar.gz --sse AES256Cleanup temporary local files
rm -rf $BACKUP_DIR ```3. Automating with Cron Job
To run the script automatically every night (at 2:00 AM):
1. Open the system scheduled tasks:
`sudo crontab -e`
2. Add the line at the end of the file:
`0 2 * * * /home/user/scripts/backup.sh > /dev/null 2>&1`
Conclusion
Having automated backup policies stored away from the source infrastructure is essential. By configuring encryption at the S3 level and monitoring the execution of these scripts, your business will be fully protected against accidental deletions, hardware disasters, or cyber attacks.