Today's fast and simple tip is about rsync.
Rsync is a powerful and efficient tool for synchronizing files and performing backups between local or remote machines. In this article, we will explore three practical scenarios for using rsync for server backups, with clear and functional examples.
1. Rsync with Basic SSH
Initial command:
rsync -rv --dry-run my_dir/ user@ip:/home/user/backup/
What do the options mean?
-
-r
: Copies directories recursively, including subfolders and files. -
-v
: Verbose mode, shows details of what is being transferred. -
--dry-run
: Simulates execution without making actual changes, ideal for testing.
This command synchronizes the my_dir/
directory to the remote server in /home/user/backup/
via SSH on the default port (22). Note the /
after my_dir/
, which indicates that the directory's contents will be copied, not the directory itself.
Functional command (without simulation):
rsync -rv my_dir/ user@ip:/home/user/backup/
Here, the backup is effectively executed. Simple and straightforward!
2. Rsync with Different SSH Port and Private Key
If the server uses a non-standard SSH port (e.g., 2222) and key-based authentication, adjust the command as follows:
rsync -rv --dry-run -e "ssh -p 2222 -i ~/.ssh/file.pem" my_dir/ user@ip:/home/user/backup/
What changed?
-
-e "ssh -p 2222 -i ~/.ssh/file.pem"
: Defines a custom SSH command: -
-p 2222
: Uses port 2222 (non-standard, different from the default 22). -
-i ~/.ssh/file.pem
: Specifies the private key for authentication.
Functional command:
rsync -rv -e "ssh -p 2222 -i ~/.ssh/file.pem" my_dir/ user@ip:/home/user/backup/
This format is useful for servers with specific security configurations.
3. Rsync with Server Name via .ssh/config
To simplify, you can configure an alias in the ~/.ssh/config
file. Example configuration:
Host SERVER
HostName server_ip
User user
Port 22
IdentityFile ~/.ssh/id_rsa
Save this in ~/.ssh/config
. Now, rsync can use the alias SERVER
:
rsync -rv --dry-run my_dir/ SERVER:/home/user/backup/
Advantages:
- Avoids typing the IP, user, and key every time.
- Makes the command cleaner and more readable.
Functional command:
rsync -rv my_dir/ SERVER:/home/user/backup/
With the alias configured, the backup runs without complications.
Extra Tip
For real backups, add options like:
-
-a
: Archive mode, preserves permissions, timestamps, and symbolic links. -
--delete
: Removes files on the destination that are no longer in the source.
Complete example:
rsync -av --delete my_dir/ SERVER:/home/user/backup/
With this, you have an efficient and up-to-date backup. Always test with --dry-run
before running it for real!
Top comments (0)