Skip to content
Advertisement

Linux systemd service file to start and stop a minecraft server

I am trying to run a minecraft server on a remote linux instance.

I would like the instance to start up the server on a screen named serverscreen which is owned by the user named minecraft once the system boots up, and run a stop command to the serverscreen when the instance shuts down. Then, it needs to wait untill the server has stopped before actually shutting down.

I am quite new to linux but I have managed to come up with a few commands that work, but I have issues trying to start and stop the server automatically.

I have tried quite a few things, like creating a .sh script to run on startup with crontab -e @reboot script.sh, or create a file in etc/rc.local with #!/bin/sh sh script.sh, but those methods didn’t seem to work properly for me. Also, they do not run un shutdown unfortunately. Therefore, I thought it would be best to create a service file named minecraft.service with the following commands:

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

[Service]
User=minecraft
Nice=5
KillMode=none
SuccessExitStatus=0 1
InaccessibleDirectories=/root /sys /srv /media -/lost+found
NoNewPrivileges=true
WorkingDirectory=/opt/minecraft/server
ReadWriteDirectories=/opt/minecraft/server

#### Command to start the server.
ExecStart=sudo -u minecraft screen -dmS serverscreen java -Xms6G -Xmx6G -jar /opt/minecraft/server/forgeserver.jar nogui

#### Command to stop the server.
ExecStop=sudo -u minecraft screen -S serverscreen -p 0 -X eval "stuff stop^M"
##### Try to wait untill the server has stopped. I am not sure about this line of code since I haven't been able to test it properly.
ExecStop=/bin/bash -c "while ps -p $MAINPID > /dev/null; do /bin/sleep 1; done"

[Install]
WantedBy=multi-user.target

but when running this, it gives me an error saying that I did not provide an absolute path for something.

Could someone help me setup a service file that will boot up the server on a screen named serverscreen for the user minecraft, and run command stop when the instance shuts down after the server has been stopped?

Advertisement

Answer

Thanks to @Riz, the service now works as intended by using a bash script in order to run the commands.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement