service files for systemd are writtern in a format similar to toml and ini
[Unit]
and[Install]
- carries generic information about the unit that is not dependent on the type of unit[Service]
- carries information about the process the service files executes
The service files need to be stored inside /etc/systemd/system
for systemd to recognize.
So we will create a file name systemd-example.service
inside /etc/systemd/system
We can specify how to start the process with the ExecStart
option under the service section:
[Service]
ExecStart=/usr/local/bin/systemd-example
We also need to specify the Type
option under the service section to tell systemd about the type of the program (i.e. is it a daemon?, will it notify systemd after it started, etc).
In our case out go program is not a daemon and is considered unactive if the process exits so we will be using the Simple
as the option for Type
:
[Service]
Type=Simple
ExecStart=/usr/local/bin/systemd-example
Since we want to restart the process the it crashes we will need set the Restart
option to always
:
[Service]
Type=Simple
Restart=always
ExecStart=/usr/local/bin/systemd-example
Next we need to specify the services that needs to be running before the process starts. which we can specify with the WantedBy
or RequiredBy
options in the install section
For the program we wrote if sockets are started it should work but to be safe we will tell systemd it requries everything required by multi-user.target
which requires everything need to setup a multi-user shell:
[Service]
Type=Simple
Restart=always
ExecStart=/usr/local/bin/systemd-example
[Install]
WantedBy=multi-user.target
We can add a description for our service under the unit section:
[Unit]
Description=Example systemd service.
[Service]
Type=Simple
Restart=always
ExecStart=/usr/local/bin/systemd-example
[Install]
WantedBy=multi-user.target
First we need to make systemd load the service file we just created this can be done by either restarting the system or running systemctl daemon-reload
systemctl start systemd-example.service
systemctl enalbe systemd-example.service