As a Mastodon server administrator, you need a reliable backup strategy to protect user data, media files, and configurations. Manual exports are time-consuming and prone to human error, especially when managing a growing instance. This article explains how to set up an automated cron job that runs a Mastodon export on a schedule, creating regular backups without manual intervention. You will learn the specific commands, scripts, and scheduling steps required to automate the export process on a Linux server.
Key Takeaways: Automated Mastodon Backup via Cron
- tootctl media remove –days=30: Removes cached media older than 30 days to reduce disk usage before export.
- pg_dump mastodon_production: Exports the PostgreSQL database to a compressed SQL file for full data recovery.
- crontab -e with 0 3 : Schedules the backup script to run daily at 3:00 AM server local time.
What the Mastodon Export Cron Job Does and Why You Need It
The Mastodon export cron job automates the process of backing up your Mastodon instance data, including the PostgreSQL database, user-uploaded media files stored on the filesystem, and configuration files such as .env.production. Without an automated backup, you risk losing all user accounts, posts, follows, media, and server settings if the server experiences hardware failure, data corruption, or a security incident. A cron job runs a shell script at defined intervals, typically daily, to create compressed archives of the critical data and optionally upload them to a remote storage location like an S3 bucket or another server.
The core components backed up by this process are:
- PostgreSQL database dump: Contains all user accounts, posts, relationships, and metadata.
- Media files directory: Contains user-uploaded images, videos, and custom emojis stored under
/home/mastodon/live/public/system. - Configuration files: The
.env.productionfile and any custom Nginx or systemd service files.
Before setting up the cron job, you must have SSH access to your Mastodon server, sudo or root privileges, and the ability to edit files in the mastodon user’s home directory. You also need to know the database credentials, which are stored in the .env.production file. The backup script will run as the mastodon user to ensure it has proper file permissions.
Steps to Create and Schedule the Backup Cron Job
Follow these steps to create a backup script and schedule it with cron. All commands are executed on the Mastodon server via SSH unless otherwise noted.
- Create the backup directory
Log into your Mastodon server. Switch to the mastodon user withsudo -i -u mastodon. Create a directory to store the backup scripts and output:mkdir -p ~/backups. This directory will hold both the shell script and the compressed backup files. - Write the backup shell script
Create a new file named~/backups/mastodon-backup.shusing a text editor like nano:nano ~/backups/mastodon-backup.sh. Paste the following script content, adjusting the paths and database name as needed for your instance:#!/bin/bash # Variables BACKUP_DIR="/home/mastodon/backups" TIMESTAMP=$(date +"%Y%m%d_%H%M%S") DB_NAME="mastodon_production" DB_USER="mastodon" MEDIA_DIR="/home/mastodon/live/public/system" # Create backup directory if it does not exist mkdir -p "$BACKUP_DIR" # Dump the PostgreSQL database pg_dump -U "$DB_USER" -d "$DB_NAME" --format=custom --file="$BACKUP_DIR/mastodon_db_$TIMESTAMP.dump" # Compress media files tar -czf "$BACKUP_DIR/mastodon_media_$TIMESTAMP.tar.gz" -C "$MEDIA_DIR" . # Compress configuration files tar -czf "$BACKUP_DIR/mastodon_config_$TIMESTAMP.tar.gz" -C /home/mastodon/live .env.production # Remove backups older than 7 days find "$BACKUP_DIR" -name "mastodon_" -type f -mtime +7 -delete echo "Backup completed at $TIMESTAMP"Save the file and exit nano.
- Make the script executable
Runchmod +x ~/backups/mastodon-backup.shto allow the script to be executed. - Test the script manually
Runbash ~/backups/mastodon-backup.shto verify it executes without errors. Check the~/backupsdirectory for the generated files:ls -la ~/backups. You should see three files with timestamps in their names. - Open the cron table for the mastodon user
Still as the mastodon user, runcrontab -e. If prompted, select your preferred text editor (nano is recommended). - Add the cron job entry
Add the following line to the end of the crontab file to run the backup daily at 3:00 AM:0 3 /bin/bash /home/mastodon/backups/mastodon-backup.sh
Save the file and exit. The cron daemon will automatically load the new schedule. - Verify the cron job is active
Runcrontab -lto list the active cron jobs. You should see the line you just added. Check the system logs withgrep CRON /var/log/syslogafter the scheduled time to confirm the job ran successfully.
Common Mistakes and Limitations When Automating Backups
Backup script fails with permission denied to PostgreSQL database
The mastodon user must have proper PostgreSQL permissions to run pg_dump. By default, the mastodon user is created as a PostgreSQL superuser during installation. If you changed the database user, update the DB_USER variable in the script and ensure that user has read access to the database. Test the command pg_dump -U mastodon -d mastodon_production --format=custom --file=/tmp/test.dump manually to verify.
Cron job runs but no backup files appear
This usually means the script encountered an error that was not captured in the output. Modify the cron job line to redirect output to a log file for debugging. Change the line to:0 3 /bin/bash /home/mastodon/backups/mastodon-backup.sh >> /home/mastodon/backups/cron.log 2>&1
Wait for the next run or trigger it manually, then check cron.log for error messages.
Backups consume too much disk space
The script includes a cleanup command that deletes backups older than 7 days. Adjust the +7 value to a different number of days if you need longer retention. For example, +14 keeps backups for two weeks. Monitor disk usage with df -h to ensure the backup directory does not fill the filesystem.
Media directory backup is too large
Mastodon media files can consume gigabytes of disk space. Before running the backup script, consider running tootctl media remove --days=30 to delete cached media older than 30 days. This command is safe to run before the backup because it only removes media that has been cached by remote instances, not user-uploaded content. Add this command to the backup script before the media compression line to reduce backup size.
Manual Export vs Automated Cron Backup
| Item | Manual Export | Automated Cron Backup |
|---|---|---|
| Frequency | On-demand, often forgotten | Scheduled, runs without fail |
| Consistency | Prone to human error and skipped steps | Identical process every time |
| Data scope | May miss config files or media | Full database, media, and config |
| Recovery speed | Requires locating and restoring files manually | Backup files are organized and ready to restore |
| Disk space management | No automatic cleanup | Automatic deletion of old backups |
With the cron job running daily, your Mastodon instance now has a consistent, automated backup routine. You can extend the script to upload the backup files to a remote server or cloud storage using rsync or aws s3 cp. For added security, encrypt the database dump with gpg before transferring it off the server. Test a full restore process at least once by importing a backup into a test instance to confirm the data is recoverable.