Linux - Systemd Service Unit for Minecraft Servers
I am currently running two Minecraft servers and planning to spin a third. However it is becoming an ordeal to manage all the tmux sessions for them. I then have decided to use systemd to manage them and create room for dynamic growth.
1) Creating the unit file
This unit is set as Type=forking where the initial process is expected to fork at least once and exit, leaving a child running.
The ExecStop= options make sure to announce that the server is shutting down to the players, stop and save the map. And finally, kill the tmux session.
After= Ensure that the unit starts after the networking.
WorkingDirectory= Sets the working directory for executed processes.
Type= The service manager will consider the unit up after the main process exits.
PrivateUsers= Sets up a new user namespace for the executed processes and configures a minimal user and group mapping.
ProtectSystem= If set to "full", the /etc/ directory is mounted read-only.
ProtectHome= If true, the directories /home/, /root, and /run/user are made inaccessible and empty for processes invoked by this unit.
ProtectKernelTunables= If true, kernel variables will be made read-only to all processes of the unit.
ProtectKernelModules= If true, explicit module loading will be denied.
ProtectControlGroups= If true, the Linux Control Groups hierarchies accessible through /sys/fs/cgroup/ will be made read-only to all processes of the unit.
Environment= Sets environment variables for executed processes.
EnvironmentFile= Similar to Environment= but reads the environment variables from a text file. Settings from this file override settings created with Enviroment=.
Restart= Configures whether the service shall be restarted when the service process exits, is killed, or a timeout is reached.
RestartSec= Configures the time to sleep before restarting a service.
The working directory is /mineserver and we just need to create folders for each server we want to run and enable/start the service according to its folder name.