Limited Interest

Minecraft Server on SIGTERM / SIGINT

Technical   Minecraft

The short answer: as far as I can tell the java Minecraft server stops safely on SIGINT / SIGTERM despite not displaying the normal stop messages.

This is based off of my short look at the official deobsfucation map and decompiled source code from the 1.17.1 server. I believe the snippets I include will not cause any issues.

The stop command essentially is the following

((CommandSourceStack)commandContext.getSource()).getServer().halt(false);

and the main function contains the following

object = new Thread("Server Shutdown Thread", (DedicatedServer)object3) {
    ...
    @Override
    public void run() {
        this.val$dedicatedServer.halt(true);
    }
};
...
Runtime.getRuntime().addShutdownHook((Thread)object);

therefore when shutting down for some reasons (such as SIGINT / SIGTERM) it shuts down safely, it does the exact same thing as calling the stop command! I believe this is because the logger disables itself with a shutdown hook, so the messages that are logged are not displayed. It’s also fairly obvious that something happens when you send an interrupt as it takes some time to exit.

This leads me on to why I care about this, and it is in making a systemd service to control a minecraft server. The file at the moment (I might update this if I have a cause to) is

[Unit]
Description=Minecraft server

Wants=network.target
After=network.target

StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
DynamicUser=true
ProtectHome=true
ExecStart=java -jar /opt/minecraft/1.17.1.jar nogui
WorkingDirectory=/var/lib/private/minecraft/main
StateDirectory=minecraft/main

Restart=always
RestartSec=5s

[Install]
WantedBy=multi-user.target

If the server crashes, or stop is run in a way not managed by systemd, it will attempt to restart up to 5 times. This is not necessary, I’ve just decided to include it.