What is systemd and what is it needed for?

systemd is an init system used in Linux. It also manages system processes after booting. So you may need to use systemd if you want to make your own service.

What is service?

service is an application running in the background. For example, Apache or MySQL are services. These apps run in background and you may do some operations using commands:

systemctl start myservice
systemctl stop myservice
systemctl restart myservice
systemctl status myservice # to check service status
systemctl reload myservice # to make service reload its settings

systemd in Ubuntu

Please note that systemd is only fully supported in Ubuntu 15.04 and later releases. In previous versions of Ubuntu Upstart was used to manage services.

How to create a service

Service configurations are written in files called units.
System units are located in /usr/lib/systemd/system
User created units are located in /etc/systemd/system

Let's create a new unit file for our service with name myservice.service and place it in /etc/systemd/system.
In that file, first of all, we will declare Unit section. We will set some description for our service and also for example let's make it start after NGINX web server service starts:

If you want, you may make other service required to be running before this service could be started. Let's require MySQL database service to be running:
Next, let's declare Service section in our config file:
In this section we may set working directory:
We can also set user and group which will be used to start the service:
Environmental variables:
And most important - commands to start / stop / reload service:
ExecStart=/path/to/your/app [args]
ExecStop=/path/to/your/app [args]
ExecReload=/path/to/your/app [args]
Please note: You need to specify full path. Here is start command example for my Java application:
ExecStart=/usr/bin/java -jar /root/apps/javaapp/javaapp.jar


Here is an example of how your myservice.service file can look like:


ExecStart=/var/www/myapp/app start-service
ExecStop=/var/www/myapp/app stop-service
ExecReload=/var/www/myapp/app reload-config

Running service

After creating this unit and placing it to /etc/systemd/system you can start it with:

systemctl start myservice
And now you can check your service status with:
systemctl status myservice

Other tips

If you want to reload systemd after making some changes to configuration, run:

systemctl daemon-reload
If you want to check service logs, run:
journalctl -u myunit
If you want specific service to start on system boot:
systemctl enable myunit
Opposite for that command (if you want your service not to be started on system boot) is:
systemctl disable myunit

That was short "cheetsheet"-like tutorial for systemd. Hopefully it helps me or anybody who reads this next time it will be needed to set up a systemd service. Anyway, I am planning to edit / extend / update this post in the future.

Thank you for reading!