Run any Executable as Systemd Service in Linux

Source

This article was originally written in my personal blog abhinand5.github.io

What is systemd?

$ systemctl list-units --type=service
systemctl list-units example
$ systemctl status postgresql
$ systemctl cat postgresql

Creating our own systemd service

$ man systemd.unit
Example from systemd manual
$ touch echo-server.service
[Unit]
Description=Service that keeps running the echo-server from startup.
[Install]
WantedBy=multi-user.target
After=network.target
[Service]
Type=simple
ExecStart=/home/abhi/Dev/echo-server/server
WorkingDirectory=/home/abhi/Dev/echo-server
Restart=always
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=%n
Type=simple
WorkingDirectory=/home/abhi/Dev/echo-server
Restart=always
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=%n

Running the Service and monitoring it

$ sudo systemctl daemon-reload
$ sudo systemctl enable echo-server.service
$ sudo systemctl start echo-server.service
$ sudo systemctl status echo-server.service
$ journalctl -f -u echo-server.service

Run a shell script as service (Alternative)

$ touch start-echo-server.sh
#!/bin/bashSCRIPT_PATH=/home/abhi/Dev/echo-server/server.py
PYTHON_PATH=/home/abhi/.local/bin/.virtualenvs/main/bin/python
$PYTHON_PATH $SCRIPT_PATHexit 1
$ which python
$ chmod +x start-echo-server.sh
$ sudo mv start-echo-server.sh /usr/sbin
Example

Removing the systemd service

$ systemctl stop echo-server.service
$ systemctl disable echo-server.service
$ sudo rm /etc/systemd/system/echo-server.service
$ systemctl daemon-reload
$ sudo rm /usr/sbin/start-echo-server.sh
$ systemctl reset-failed

Conclusion

Thanks a ton for reading all the way. If you like the article feel free to hit that clap icon which motivates me to write more good articles.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store