systemd & systemctl
systemd
https://systemd.io/
System and Service Manager
systemd is a suite of basic building blocks for a Linux system. It provides a system and service manager that runs as PID 1 and starts the rest of the system.
systemd provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points, and implements an elaborate transactional dependency-based service control logic. systemd supports SysV and LSB init scripts and works as a replacement for sysvinit.
Other parts include a logging daemon, utilities to control basic system configuration like the hostname, date, locale, maintain a list of logged-in users and running containers and virtual machines, system accounts, runtime directories and settings, and daemons to manage simple network configuration, network time synchronization, log forwarding, and name resolution.
https://www.linux.com/training-tutorials/understanding-and-using-systemd/
systemctl 和 service
https://zhuanlan.zhihu.com/p/627047621
在 Linux 系统中,我们经常需要管理和控制系统服务。两个主要的命令用于此目的是
systemctl
和service
。尽管它们都用于管理服务,但它们与不同的初始化系统(init system)相关。在本文中,我们将讨论systemctl
和service
之间的区别以及如何查看service
是否被映射到systemctl
。1.
systemctl
和systemd
systemctl
是与systemd
初始化系统相关的命令。systemd
是许多现代 Linux 发行版(如 Ubuntu、Fedora、Debian 等)的默认初始化系统。systemd
采用了并行启动方式,提供了更快的启动速度和更高的灵活性。systemctl
是systemd
的主要命令行工具,用于控制和管理系统服务、挂载点、设备等。2.
service
和SysVinit/Upstart
service
命令与传统的SysVinit
和Upstart
初始化系统相关。较早期的 Linux 发行版(如早期的 Ubuntu、Red Hat 等)使用了这些初始化系统。service
命令用于启动、停止、重启和查询系统服务的状态。虽然许多现代 Linux 发行版已经转向使用systemd
,但它们通常仍然提供service
命令作为向后兼容支持。
How to create a systemd service in Linux
https://linuxhandbook.com/create-systemd-services/
Understanding the basic structure of a systemd service file
The systemd service file has three important and necessary sections. They are
[Unit]
,[Service]
and[Install]
sections. The systemd service file's extension is.service
and we use the pound/hash symbol (#
) for single line comments.Below is an example of a systemd service file. Please note that this is NOT an actual systemd service file. I have modified it so that it helps you understand.
[Unit] Description=Apache web server After=network.target Before=nextcloud-web.service [Service] ExecStart=/usr/local/apache2/bin/httpd -D FOREGROUND -k start ExecReload=/usr/local/apache2/bin/httpd -k graceful Type=notify Restart=always [Install] WantedBy=default.target RequiredBy=network.target
This is the most basic structure of a systemd service file. Let us understand what each of these words mean.
The
[Unit]
sectionThe Unit section contains details and description about the unit itself. In our case, it contains details about the service. Details like 'what is its description', 'what are its dependencies' and more.
Below are the fields the Unit section has:
Description
:- Human-readable title of the systemd service.After
:- Set dependency on a service. For example, if you are configuring Apache web server, you want the server to start after the network is online. This typically includes targets or other services.Before
:- Start current service before specified service. In this example, I tell that "I want Apache web server running before the service for Nextcloud is started". This is because, in my case, Nextcloud server depends on the Apache web server. This too, likeAfter
, includes targets or other services.The
[Service]
sectionThe Service section contains details about the execution and termination of service.
Below are the fields the Service section has:
ExecStart
:- The command that needs to be executed when the service starts. In our case, we want the Apache server to start.ExecReload
:- This is an optional field. It specifies how a service is restarted. For services that perform disk I/O (especially writing to disk, like a database), it is best to gracefully kill them and start again. Use this field in case you wish to have a specific restart mechanism.Type
:- This indicates the start-up type of a process for a given systemd service. Options aresimple
,exec
,forking
,oneshot
,dbus
,notify
andidle
. (more info here)Restart
:- This is another optional field but one that you will very likely use. This specifies if a service should be restarted--depending on circumstances--or not. The available options areno
,on-success
,on-failure
,on-abnormal
,on-watchdog
,on-abort
andalways
.The
[Install]
sectionThe Install section, as the name says, handles the installation of a systemd service/unit file. This is used when you run either
systemctl enable
andsystemctl disable
command for enabling or disabling a service.Below are the fields the Install section has:
WantedBy
:- This is similar to theAfter
andBefore
fields, but the main difference is that this is used to specify systemd-equivalent "runlevels". Thedefault.target
is when all the system initialization is complete--when the user is asked to log in. Most user-facing services (like Apache, cron, GNOME-stuff, etc.) use this target.RequiredBy
:- This field might feel very similar toWantedBy
, but the main difference is that this field specifies hard dependencies. Meaning, if a dependency, this service will fail.What I have listed above, is only a minimal example. There are loads of knobs that you can turn to customize your service depending on your environment and needs.
For a complete documentation about systemd, please refer to this page. This literally has everything documented!
systemctl
https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units
Starting and Stopping Services
To start a
systemd
service, executing instructions in the service’s unit file, use thestart
command. If you are running as a non-root user, you will have to usesudo
since this will affect the state of the operating system:As we mentioned above,
systemd
knows to look for*.service
files for service management commands, so the command could be typed like this:Although you may use the above format for general administration, for clarity, we will use the
.service
suffix for the remainder of the commands, to be explicit about the target we are operating on.To stop a currently running service, you can use the
stop
command instead:Restarting and Reloading
To restart a running service, you can use the
restart
command:If the application in question is able to reload its configuration files (without restarting), you can issue the
reload
command to initiate that process:If you are unsure whether the service has the functionality to reload its configuration, you can issue the
reload-or-restart
command. This will reload the configuration in-place if available. Otherwise, it will restart the service so the new configuration is picked up:Enabling and Disabling Services
The above commands are useful for starting or stopping services during the current session. To tell
systemd
to start services automatically at boot, you must enable them.To start a service at boot, use the
enable
command:This will create a symbolic link from the system’s copy of the service file (usually in
/lib/systemd/system
or/etc/systemd/system
) into the location on disk wheresystemd
looks for autostart files (usually/etc/systemd/system/some_target.target.wants
. We will go over what a target is later in this guide).To disable the service from starting automatically, you can type:
This will remove the symbolic link that indicated that the service should be started automatically.
Keep in mind that enabling a service does not start it in the current session. If you wish to start the service and also enable it at boot, you will have to issue both the
start
andenable
commands.Checking the Status of Services
To check the status of a service on your system, you can use the
status
command:This will provide you with the service state, the cgroup hierarchy, and the first few log lines.
For instance, when checking the status of an Nginx server, you may see output like this:
Output● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled) Active: active (running) since Tue 2015-01-27 19:41:23 EST; 22h ago Main PID: 495 (nginx) CGroup: /system.slice/nginx.service ├─495 nginx: master process /usr/bin/nginx -g pid /run/nginx.pid; error_log stderr; └─496 nginx: worker process Jan 27 19:41:23 desktop systemd[1]: Starting A high performance web server and a reverse proxy server... Jan 27 19:41:23 desktop systemd[1]: Started A high performance web server and a reverse proxy server.
This gives you a nice overview of the current status of the application, notifying you of any problems and any actions that may be required.
There are also methods for checking for specific states. For instance, to check to see if a unit is currently active (running), you can use the
is-active
command:This will return the current unit state, which is usually
active
orinactive
. The exit code will be “0” if it is active, making the result simpler to parse in shell scripts.To see if the unit is enabled, you can use the
is-enabled
command:This will output whether the service is
enabled
ordisabled
and will again set the exit code to “0” or “1” depending on the answer to the command question.A third check is whether the unit is in a failed state. This indicates that there was a problem starting the unit in question:
This will return
active
if it is running properly orfailed
if an error occurred. If the unit was intentionally stopped, it may returnunknown
orinactive
. An exit status of “0” indicates that a failure occurred and an exit status of “1” indicates any other status.
https://www.digitalocean.com/community/tutorials/systemd-essentials-working-with-services-units-and-the-journal
Querying Unit States and Logs
While the above commands gave you access to the general system state, you can also get information about the state of individual units.
To see an overview of the current state of a unit, you can use the
status
option with thesystemctl
command. This will show you whether the unit is active, information about the process, and the latest journal entries:To see all of the journal entries for the unit in question, give the
-u
option with the unit name to thejournalctl
command:As always, you can limit the entries to the current boot by adding the
-b
flag:
- journalctl -b -u nginx.service