At times you create a script and then you want to have the scripts controlled by systemd or in some cases you wish to have the scripts getting restarted by itself when it is killed due to some reason.
Systemd in Linux helps to configure services which can be managed.
In this article, We will show you how to create systemd service.
Create systemd service
In general
Just follow the steps below:
- You can find running linux service under path /etc/systemd/system
cd /etc/systemd/system
- Create a file named [servicename.service] and add the following
[Unit]
Description=<description_about_your_service>
[Service]
User=<user_such_as_root>
WorkingDirectory=<directory_of__your_script such as /home/unixcop>
ExecStart=<script_which_needs_to_be_executed>
Restart=always
[Install]
WantedBy=multi-user.target
NOTE: Replace the Bold values above with your values of your new service that you want to create.
A service unit is a file with the .service suffix contains information about a process which managed by systemd. It is composed by three main sections:
- [Unit]: this section contains information not specifically related to the type of the unit, such as the service description
- [Service]: contains information about the specific type of the unit, a service in this case
- [Install]: This section contains information about the installation of the unit
For Python specific projects which include virtual environment
- Follow the same steps above but add the following
[Unit]
Description=<description_about_your_project>
[Service]
User=<user_such_as_root>
WorkingDirectory=<path/to/your/project/directory/containing/the/python/script>
ExecStart=Path of virtualenv and your script file name
#Example for ExecStart=/home/user/.virtualenv/bin/python main.py
#replace /home/user/.virtualenv/bin/python with your virtualenv and main.py with your script name
Restart=always
[Install]
WantedBy=multi-user.target
OR
[Unit]
Description=<description_about_your_project>
[Service]
User=<user_such_as_root>
WorkingDirectory=<path to your project directory>
ExecStart=/bin/bash -c 'cd /home/unixcop/project/ && source venv/bin/activate && python test.py'
#replace /home/unixcop/project/ with your Path, venv/bin/activate with your source and test.py with your script name
[Install]
WantedBy=multi-user.target
- After you finish reload the service files to include the new service.
sudo systemctl daemon-reload
- Start your new service
sudo systemctl start [your_new_service].service
- Check the status of your new service e.g (my new service called unixcop.service)
sudo systemctl status unixcop.service
- Enable your service on every reboot
sudo systemctl enable unixcop.service
- To disable your service on every reboot
sudo systemctl disable unixcop.service
Conclusion
That’s it
We illustrated how to create a new systemd service in Linux
Thanks !!