What is it? Why use it?
Systemd is a linux service to manage and configure services. It is used for automated startup, to make sure that an application gets started on boot basically.
If you want a service to start at startup, that's where you do it.
How to define and start a systemd service?
You have your program and you want it to start at each boot. You create a myService.service file inside of /etc/systemd/system/
Each object managed by system is called a Unit. A service is a unit for example (recognised by its .service ending).
Example:
[Unit]
Description=My Custom Service
After=network.target
[Service]
ExecStart=/usr/bin/my-custom-service
Restart=always
User=myuser
Group=mygroup
[Install]
WantedBy=multi-user.target
Unit
Description
: Just for documentation.
After
: When it gets started. This is not a dependency just sets the order in which services are started. It doesn't guarantee that the specified unit is running. However here with network.target it just works.
Service
ExecStart=<Full path and arguments of the command to be executed to start the process>
Restart=
under which circumstances it will try to restart the process.
User and group define who runs this service. The user and group need to have the access rights to execute the programs and access all files that are accessed.
Install
Defined how it should be started. This is a dependency.
WantedBy=multi-user.target
means the service multi-user.target wants this service. It will get activated/started right after multi-user.target is activated.
Usage
We interact with it via systemctl
{bash} sudo systemctl start nginx.service
By default systemd unit files are not started automatically on boot. They need to be enabled before.
{bash} sudo systemctl enable nginx.service
or to disable:
systemctl disable nginx.service
View all services:
{bash} systemctl list-units
See logs
{bash} journalctl -b
The {bash}-b
is to filter for the current boot.
{shell} -f
is to show only tail and update if new messages come in.
{bash} journalctl -u <service name> -f
check a specific service
{bash} systemctl status nginx.service
Security
systemd-analyze security <myService.service>
Scroll down and check the overall score. It is probably bad. 9.x UNSAFE
If you want to fix this do it following this guide for example:
Doesn't seem too hard.Debugging:
On each change of your service, you need to:
- Reload Daemon:
sudo systemctl daemon-reload
- Restart your service:
sudo systemctl restart myService.service
Then check if it is running properly:
sudo systemctl status myService.service
Optionally: Check the syntax:
sudo systemd-analyze verify myService.service
Check the logs:
{bash} sudo journalctl -u django_base.service