How to create a systemd service?

We will use a Minecraft server as an example. This is a java application. It should start when the machine boots up and it stops gracefully when the service is stopped. The service name will be minecraft.

Create a text file at the following location: /etc/systemd/system/minecraft.service

Below is the content of the file:

[Unit]
Description=Minecraft
After=network.target

[Service]
WorkingDirectory=/home/minecraft/Minecraft_Server
ExecStart=/usr/bin/java -Xms1G -Xmx1G -jar server.jar nogui
User=minecraft
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

Most of those settings are self-descriptive. When the service stops, it sends SIGTERM to the java process. Minecraft handles that signal and exits with exit code 143. In this case the exit code is expected. For that reason, it is assigned to the success status.

If you wish to set environmental variables for your service, add the following settings:

[Service]
Environment=PLAYERNAME=JOHN
Environment=PLAYERSKILL=EASY

The variables are for example only. They are not supported by Minecraft.

Next, enable the service and start:

systemctl enable minecraft
systemctl start minecraft

You can monitor the output:

journalctl -f u minecraft