Here are simple steps to backup your VPS.
Create a directory to store the backup files. Then run mysqldump
command to backup your database.
mysqldump -u your_mysql_user -pyour_mysql_password your_database_name > /path/to/dump_$(date +\%Y\%m\%d\%H\%M\%S).sql
Or you run it as supersuer and backup all databases in once.
sudo mysqldump --all-databases > /path/to/dump_$(date +\%Y\%m\%d\%H\%M\%S).sql
To automate this, schedule a cron job that will run this command on a daily basis.
crontab -e
Insert the following line to execute the mysqldump command every day at midnight.
0 0 * * * mysqldump -u your_mysql_user -pyour_mysql_password your_database_name > /path/to/dump_$(date +\%Y\%m\%d\%H\%M\%S).sql
I use rsync and following bash script to backup my files. I manually execute it from my local machine but could easily be scheduled as a cron job and/or run from a different VPS.
#!/bin/bash
REMOTE_USER="user"
REMOTE_HOST="host"
LOCAL_BACKUP_DIR="/path/to/local/backup/directory"
# Ensure local backup directory exists
mkdir -p $LOCAL_BACKUP_DIR
rsync -avz $REMOTE_USER@$REMOTE_HOST:/path/to/database_backup $LOCAL_BACKUP_DIR/database_backup
# Backup /var/www/ and delete files that no longer exist on remote
rsync -avz --delete $REMOTE_USER@$REMOTE_HOST:/var/www/ $LOCAL_BACKUP_DIR/var_www/
echo "Backup completed."
And there you have it—a simple, yet effective way to backup both your MySQL databases and essential files on your VPS.