Automate Your Server: Create your own custom services with Systemd
1 min read

Automate Your Server: Create your own custom services with Systemd

Have you ever had problems with i.e. having to start a Minecraft server every time you had restarted your server? That's a problem of the past if you create a custom service!

Requirements:
* A working Minecraft Server
* Systemd
* The Aptitude package manager
* Sudo or root priviledges

I am going to use a Minecraft server as an example, because I have the script already.

# Update package manager's repositories
sudo apt update

# Install dependencies (asuming you've already installed that particular Minecraft server
sudo apt install screen -y

Cool! Now the needed programs are installed!

Let's change our working directory to the one where we will need to put our custom service! (To verify the folder exists)

cd /etc/systemd/system

Nice, you're there. If the folder doesn't exist, create it using:

sudo mkdir -p /etc/systemd/system/

Now create a file for our Minecraft Server service (I will call it 'minecraft.service')

sudo touch /etc/systemd/system/minecraft.service

Now edit the file using your favorite editor. Mine is Neovim so I'll use that but Nano or Emacs is also great!

sudo nvim /etc/systemd/system/minecraft.service

Add the following and fill the spots I've left for you.

[Unit]
Description=Minecraft Server
After=network.target

[Service]
WorkingDirectory=/path/to/your/server/directory

User=yourusername
Group=yourgroupname (usually your username)

Restart=always

ExecStart=/usr/bin/screen -DmS mc /usr/bin/java -Xmx12G -jar spigot.jar nogui

ExecStop=/usr/bin/screen -p 0 -S mc -X eval 'stuff "say Server is shutting down in 10 seconds."\015'
ExecStop=/bin/sleep 10
ExecStop=/usr/bin/screen -p 0 -S mc -X eval 'stuff "save-all"\015'
ExecStop=/usr/bin/screen -p 0 -S mc -X eval 'stuff "stop"\015'


[Install]
WantedBy=multi-user.target

Cool! Check if Systemd sees your service with the following command:

sudo systemctl status minecraft.service

If it sees it, stop your server if it is running and run:

sudo systemctl start minecraft.service

Now check if it's up using this command again:

sudo systemctl status minecraft.service

Now your service should work! As a little bonus, this:

sudo systemctl status minecraft.service

Enables it at startup :)

Have fun crafting!