Automate Minecraft backups: script, schedule, restore

A backup script for a running Minecraft server, scheduled with cron or a Pterodactyl schedule, with retention, an off-site copy and a restore check.

Omne TeamUpdated Nov 17, 202611 min read

Quick answer The safe order is save-off, save-all flush, copy the whole world folder, save-on [1]. The script below does that over RCON, checks the archive contains level.dat, keeps the newest 14 copies and can push each one off the machine. Run it from cron once a night. On a Pterodactyl panel you cannot run scripts, so chain the same commands and the Backup task in a schedule, with the delays described below.

The old version of this post said what to automate and never showed how. This one has three parts: a script for any Linux machine that hosts your server, the same sequence as a Pterodactyl schedule, and a restore test, because an untested backup is a guess.

Which path you are on

Own machine or VPS with a shell Pterodactyl panel (you are a customer)
What runs the backup mc-backup.sh from cron A schedule with command and backup tasks
Flushes the world first Yes, the script sends the commands Only if you add the command tasks
Where the archive goes DEST, then optionally rsync or rclone Wherever the panel’s backup driver points
Retention Newest KEEP archives The server’s backup limit; a scheduled backup replaces the oldest unlocked one [6][8]

If you are still deciding where to run the server, self-hosting on your own PC and renting one lead to different columns of this table.

The script

It needs RCON switched on (the RCON setup post covers the server.properties lines and why the port stays firewalled) and the mcrcon client. mcrcon reads the password from the MCRCON_PASS environment variable, so you do not pass -p, and commands with spaces need quotes [2].

#!/usr/bin/env bash
# Consistent world backup over RCON. Needs mcrcon and MCRCON_PASS in the environment.
set -euo pipefail

SERVER_DIR=${SERVER_DIR:-/srv/minecraft}
DEST=${DEST:-/srv/backups}
KEEP=${KEEP:-14}              # how many archives to keep
FLUSH_WAIT=${FLUSH_WAIT:-5}   # seconds to wait after "save-all flush"
OFFSITE=${OFFSITE:-}          # optional rsync destination, e.g. user@host:/backups/
: "${MCRCON_PASS:?set MCRCON_PASS first}"
RCON="mcrcon -H ${RCON_HOST:-127.0.0.1} -P ${RCON_PORT:-25575}"

LEVEL=$(sed -n 's/^level-name=//p' "$SERVER_DIR/server.properties" | tr -d '\r')
LEVEL=${LEVEL:-world}
STAMP=$(date +%F-%H%M%S)
OUT="$DEST/$LEVEL-$STAMP.tar.gz"
mkdir -p "$DEST"

# Some servers keep the Nether and End in sibling folders (world_nether, world_the_end); include them if present.
DIRS=("$LEVEL")
for d in "${LEVEL}_nether" "${LEVEL}_the_end"; do
  if [ -d "$SERVER_DIR/$d" ]; then DIRS+=("$d"); fi
done

# Whatever happens below, turn saving back on and leave no half-written archive.
SAVE_IS_OFF=1
trap 'rm -f "$OUT.tmp"; if [ "$SAVE_IS_OFF" = 1 ]; then $RCON save-on >/dev/null || true; fi' EXIT

$RCON -w 2 save-off "save-all flush" >/dev/null
sleep "$FLUSH_WAIT"
tar -czf "$OUT.tmp" -C "$SERVER_DIR" "${DIRS[@]}"
$RCON save-on >/dev/null   # back on before the slow steps (check, prune, upload)
SAVE_IS_OFF=0

# An archive that cannot be listed or has no level.dat is not a backup.
tar -tzf "$OUT.tmp" | grep -x "$LEVEL/level.dat" >/dev/null || { echo "no $LEVEL/level.dat in archive" >&2; exit 1; }
mv "$OUT.tmp" "$OUT"

# Prune only after a good new archive exists. The newest KEEP stay.
ls -1t "$DEST/$LEVEL"-*.tar.gz | tail -n +$((KEEP + 1)) | xargs -r rm --

if [ -n "$OFFSITE" ]; then rsync -a "$OUT" "$OFFSITE"; fi
echo "ok $OUT $(du -h "$OUT" | cut -f1)"

Why it is built this way:

  • It archives the whole level-name folder instead of naming region or player folders. Minecraft 26.1 moved the Nether and End under dimensions/minecraft/ inside the world folder [12], so a script that names folders breaks quietly after an update. A script that archives the folder does not care. The migration post has the new layout.
  • The trap is the important line. save-off stops the server writing level files [1]. If tar dies on a full disk and the script just exits, you are left with a server that is not saving. The trap sends save-on on every exit path. The wiki also says save-off leaves player, advancement and stat files alone [1], so those can still change while tar runs.
  • The level.dat check catches a level-name that points at a real folder that is not your world. tar will happily archive a folder you did not mean. The grep has no -q on purpose: under pipefail, grep -q exits at the first match, tar is killed by SIGPIPE on a large listing, and a good archive gets thrown away as bad.
  • Pruning comes last. Deleting by age (find -mtime +14 -delete) looks equivalent until backups fail for two weeks and the job deletes every good copy. Counting from the newest, after a checked archive exists, cannot do that.
  • FLUSH_WAIT=5 is a guess. The wiki says save-all flush saves everything immediately and freezes the server for a short time [1]. I could not confirm whether the RCON reply comes back only after that finishes, so the script waits a few seconds anyway. Raise it for a big world.

What I ran: this script against a stub mcrcon that logs its arguments, on throwaway folders. Not a real server, not real mcrcon. Results: a folder with the 26.1 dimensions/minecraft/ layout and a world plus world_nether plus world_the_end set both archived, and a world with 30,000 region-file names archived too (with grep -q in the check, that one was discarded as bad); with KEEP=2, four runs left the two newest; an unreadable file made tar print tar: world/level.dat: Cannot open: Permission denied, exit 2, leave no archive and still send save-on; a level-name pointing at a real folder without level.dat was refused, while one pointing at a missing folder failed in tar (Cannot stat, exit 2) and left no archive; a failing RCON connection stopped the script before tar. The calls the stub logged for one run:

mcrcon -H 127.0.0.1 -P 25575 -w 2 save-off save-all flush
mcrcon -H 127.0.0.1 -P 25575 save-on

Run it from cron

Put the password in a file only your server user can read, not in the crontab:

# /etc/mc-backup.env, then: chmod 600 /etc/mc-backup.env
export MCRCON_PASS='your-rcon-password'

Then crontab -e as the user that owns the server:

PATH=/usr/local/bin:/usr/bin:/bin
15 4 * * * . /etc/mc-backup.env && flock -n /tmp/mc-backup.lock /usr/local/bin/mc-backup.sh >> $HOME/mc-backup.log 2>&1

The five fields are minute, hour, day of month, month and day of week [3], so that is 04:15 every day. Pick a time when nobody is online, because the server freezes briefly during the flush [1]. Three details earn their place:

  • flock -n makes a second run give up instead of overlapping the first [4]. It exits with status 1 and prints nothing, which I confirmed against a held lock.
  • The PATH= line is there because the crontab man page does not say what PATH a cron job gets [3]. If the log says mcrcon: command not found, this is why.
  • If you ever put date +%F straight into a crontab line, escape the percent signs: an unescaped % is turned into a newline [3]. The script keeps its date logic inside itself for that reason.

After the first night, read $HOME/mc-backup.log. You should see one line like ok /srv/backups/world-2026-11-18-041500.tar.gz 1.2G (example, your date, path and size will differ). If the file does not exist, cron never ran the job.

Do the same on a Pterodactyl panel

A panel customer has no shell and no cron. The panel’s Schedules tab has the pieces: a cron time, and tasks that send a console command, send a power action or create a backup [7]. I read the panel and Wings source to see how these behave, so this section describes code, not a live panel I clicked through.

Three facts from the source decide how you build the chain:

  1. The backup task does not flush the world. Wings archives the server directory [11]. I found no save-all step in the backup code of either repository, so add the commands yourself.
  2. The backup task returns before the backup is done. The panel asks Wings to start it, and Wings runs the archive in the background and answers 202 straight away [10]. The next task’s delay counts from there [6]. A save-on task set to 0 seconds after the backup task therefore fires while the archive is still being written. I compared these files with the latest tagged releases (panel v1.15.2, Wings v1.13.5) and they are identical there.
  3. A task’s delay is capped at 900 seconds [7], and each task waits its delay after the previous one finishes [6].

A chain that works, if your backup finishes inside the last delay:

# Action Payload Delay after previous
1 Send command save-off 0 s
2 Send command save-all flush 5 s
3 Create backup (ignore list optional) 10 s
4 Send command save-on longer than your backup takes, up to 900 s

Run it once by hand and time the backup before you choose task 4’s delay. If your backup takes longer than 15 minutes, the chain cannot cover it. Drop tasks 1 and 4, keep save-all flush before the backup, and accept that a copy taken while the server is writing can catch a chunk mid-write.

Use the schedule’s only-when-online option if your panel shows it: with it set, the panel skips the run when the server is offline or stopping [9].

The failure to plan for. If the backup task throws, the chain stops and task 4 never runs, so saving stays off [6]. That happens when the server is at its backup limit and every backup is locked, when the limit is 0, or when the panel’s backup throttle trips [8]. The task’s continue-on-failure switch does not rescue this: the code only lets the chain continue when the failure is a lost connection to Wings [6]. At the limit, a scheduled backup deletes the oldest unlocked backup to make room [6][8], so lock the backups you care about and nothing else. Then add a second schedule that sends only save-on, 30 minutes after the first. If saving is already on, the wiki lists that as a failed command [1], which by my reading changes nothing. I did not test that on a panel.

Where the archive lands depends on the panel’s backup driver. Wings has a local adapter and an S3 adapter [10]. If yours is local, the archive sits on the same node as the world, so download one now and then.

Get a copy off the machine

Archives next to the world protect you from a bad edit and a griefer, not from the disk dying. The script’s OFFSITE variable runs rsync -a to another host. For object storage, rclone copy is the same idea: it copies the source to the destination, skips identical files and never deletes anything at the destination [5]:

rclone copy /srv/backups/ remote:minecraft-backups

Because copy never deletes, off-site retention is a separate decision, usually a lifecycle rule on the bucket. I ran rsync only against a local folder and did not run rclone against a real remote.

Whole-archive copies get slower as worlds grow, because this script archives the whole world every run. If that becomes a problem, a deduplicating backup tool is the usual next step; this post does not cover one.

Prove a restore works

Do this the first night and after any change to the script.

Quick check, no server needed. Extract the newest archive somewhere harmless:

latest=$(ls -1t /srv/backups/world-*.tar.gz | head -1)
scratch=$(mktemp -d)
tar -xzf "$latest" -C "$scratch" && test -s "$scratch/world/level.dat" && echo "level.dat ok, files: $(find "$scratch/world" -type f | wc -l)"
rm -rf "$scratch"

You should see level.dat ok and a file count that fits a world with region files and player data. On my throwaway folder, diff -r of the live and extracted trees came back identical. That says nothing about a real world’s size or timing, and I did not measure one.

Real restore. With the server stopped, so nothing is writing to the folder you are replacing:

  1. Rename the live folder (mv world world.broken). Do not delete it yet.
  2. tar -xzf /srv/backups/world-<stamp>.tar.gz -C /srv/minecraft
  3. Confirm level-name in server.properties still matches the folder.
  4. Start the server, join, and look at something you built yesterday.

The full proof is the same extraction into a second server directory on a different port, started and joined once. I did not do that for this post: it needs a running Minecraft server and its EULA accepted. It is the one check that tells you the world loads, not just that the files unpack.

When it fails

  • Nothing happens at 04:15. Read the log file. If it does not exist, cron never ran the command: check the user’s crontab and the PATH= line. If it says mcrcon: command not found, use the full path.
  • tar: ...: Cannot open: Permission denied, exit 2. The user running cron cannot read part of the world, for example because the server was once started as root. chown -R the server folder to the server user. By then the script has already sent save-on.
  • no <name>/level.dat in archive. level-name in server.properties names a folder that exists but is not your world, or is empty. Fix the name. The script discards the archive on purpose. If the folder does not exist at all, you get tar: ...: Cannot stat: No such file or directory and exit 2 instead.
  • Schedule ran, saving stayed off, on a panel. The backup task threw and the chain stopped before save-on. Check the server’s backup limit and locks, send save-on by hand, and add the safety-net schedule above.

Before a version upgrade, take a manual archive and keep it out of the rotation. Upgrades are one-way for world files, as the update walkthrough explains, and 14 nightly copies will eventually overwrite the last pre-upgrade one.

Questions people ask

Can I just copy the world folder while the server is running?

Not reliably. The server keeps writing region files, and a copy can catch a chunk half written. The wiki describes save-off as the command that stops level-file writes so you can copy them for backup [1]. Pair it with save-all flush so the files on disk are current before you copy.

How many backups should I keep?

Keep a fixed count, not an age. The script below keeps the newest 14 and only prunes after a new archive passes its check, so a stretch of failed backups cannot delete the last good ones.

Does the Pterodactyl Backups tab save the world first?

I found no save or flush step in Wings' backup code [10][11], so assume it does not. Add save-off and save-all flush tasks to a schedule ahead of the backup task.

How do I know a backup works?

Extract the newest archive into a scratch folder and check that level.dat is there and not empty. The only full proof is starting a second server on the extracted copy, which is worth doing once.

Sources

  1. /save (Minecraft Wiki)
  2. mcrcon README (Tiiffi/mcrcon on GitHub)
  3. crontab(5) man page
  4. flock(1) man page
  5. rclone copy
  6. Pterodactyl panel: RunTaskJob.php (1.0-develop)
  7. Pterodactyl panel: StoreTaskRequest.php (1.0-develop)
  8. Pterodactyl panel: InitiateBackupService.php (1.0-develop)
  9. Pterodactyl panel: ProcessScheduleService.php (1.0-develop)
  10. Pterodactyl Wings: router_server_backup.go (develop)
  11. Pterodactyl Wings: server/backup.go (develop)
  12. Minecraft Wiki: Java Edition level format