Recently, I was addicted to Minecraft. And I hosted a server.

In order to backup the server automatically, I have tried many solutions.

Git solution

Git solution requires a lot of CPU when compressing the objects. And may impact the game performance since Java itself requires a lot of CPU.

So I finally gave up Git.

 

Copy solution

Copy the world folder to anther place is super simple.

Before try the copy file solution, I used tmux to run the mc environment.

First, run the following command to start tmux:

$ tmux new -s mc

And in tmux, run start.sh to start your mc.

anduin@MC:~/papermc$ ls
banned-ips.json      bukkit.yml  commands.yml  help.yml   
logs      papermc.jar  permissions.yml  server.properties  start.sh        version_history.json  whitelist.json  world_nether
banned-players.json  cache       eula.txt      libraries  ops.json  paper.yml    plugins          spigot.yml         usercache.json  versions              world           world_the_end
anduin@MC:~/papermc$ cat ./start.sh
#!/bin/bash
java -Xmx3000M -Xms3000M -jar papermc.jar --nogui
anduin@MC:~/papermc$

 

After starting in tmux, you can press: Ctrl + b, d To quit tmux. And run tmux a to resume the terminal.

Finally, put the following code on your server as backup.sh. And run it with some background job system like crontab to enable auto backup.

#!/bin/bash
game_path="/home/anduin/papermc"
backup_path="/home/anduin/auto-backups"
tmux_session="mc"
folder_name=$(date +%Y-%m-%d_%H-%M-%S)

echo "Will start backup from $game_path to $backup_path/$folder_name..."
echo "Saving the game..."

tmux send-keys -t $tmux_session "say Server backup started..." Enter
tmux send-keys -t $tmux_session "save-off" Enter
tmux send-keys -t $tmux_session "save-all" Enter
sleep 30

echo "Copying the files..."
cp -r $game_path/world/ $backup_path/$folder_name/

echo "Removing the old backups..."
if [ $(ls $backup_path | wc -l) -gt 10 ]
then
        echo "Remove 1 oldest backup..."
        rm "$backup_path/$(ls $backup_path -t | tail -1)" -rf
fi

tmux send-keys -t $tmux_session "save-on" Enter
tmux send-keys -t $tmux_session "say Backup finished!" Enter
echo "Backup success!"