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.serviceand 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.targetThis 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,notifyandidle. (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-abortandalways.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 enableandsystemctl disablecommand for enabling or disabling a service.Below are the fields the Install section has:
WantedBy:- This is similar to theAfterandBeforefields, but the main difference is that this is used to specify systemd-equivalent "runlevels". Thedefault.targetis 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
systemdservice, executing instructions in the service’s unit file, use thestartcommand. If you are running as a non-root user, you will have to usesudosince this will affect the state of the operating system:As we mentioned above,
systemdknows to look for*.servicefiles 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
.servicesuffix 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
stopcommand instead:Restarting and Reloading
To restart a running service, you can use the
restartcommand:If the application in question is able to reload its configuration files (without restarting), you can issue the
reloadcommand to initiate that process:If you are unsure whether the service has the functionality to reload its configuration, you can issue the
reload-or-restartcommand. 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
systemdto start services automatically at boot, you must enable them.To start a service at boot, use the
enablecommand:This will create a symbolic link from the system’s copy of the service file (usually in
/lib/systemd/systemor/etc/systemd/system) into the location on disk wheresystemdlooks 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
startandenablecommands.Checking the Status of Services
To check the status of a service on your system, you can use the
statuscommand: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-activecommand:This will return the current unit state, which is usually
activeorinactive. 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-enabledcommand:This will output whether the service is
enabledordisabledand 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
activeif it is running properly orfailedif an error occurred. If the unit was intentionally stopped, it may returnunknownorinactive. 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
statusoption with thesystemctlcommand. 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
-uoption with the unit name to thejournalctlcommand:As always, you can limit the entries to the current boot by adding the
-bflag:
- journalctl -b -u nginx.service


浙公网安备 33010602011771号