Systemctl
The SYSTEMCTL is the primary command for querying and controlling Systemd, and the following example describes the common parameters in Mongod:
MongoDB is a very common NoSQL database under Node.js, ArchLinux by Pacman Installation: Pacman Install, MongoDB is available Mongod service after successful installation.
# View service Status
Systemctl Status Mongod
# Start Service
Systemctl Start Mongod
# Stop Service
Systemctl Stop Mongod
# Restart Service
Systemctl Restart Mongod
# Set to self-boot
Systemctl Enable Mongod
# Cancel Self-booting
Systemctl Disable Mongod
Find out more about man Page:man Systemctl
Unit file
Each SYSTEMD service is defined by a single unit file. These unit files are located in/usr/lib/systemd/system/and/etc/systemd/system/, which store the installation packages (such as MongoDB) and the system administrator's unit files. The SYSTEMD will scan the above path and load the corresponding unit when it starts.
So after you modify or add a unit file, you need to have the systemd reload the scan and load the files:
sudo systemctl daemon-reload
The syntax for a cell file is very simple, similar to the Windows. ini file. For example:
[Unit]
Description=myapp
[Service]
Workingdirectory=/home/harttle/myapp
Execstart=/usr/bin/node bin/www
Restart=always
Standardoutput=syslog
Standarderror=syslog
Syslogidentifier=myapp
Save the file as/etc/systemd/system/myapp.service and run Systemctl start MyApp to start it. View the status through the Systemctl status MyApp, and view the log by Journalctl, see below.
More information can be queried by man Page:man Systemd.unit
Monitoring log
SYSTEMD uses cgroups to monitor processes, which means that the resulting subprocess will not be detached from the log. The default log output of the SYSTEMD unit is syslog and can be viewed by journalctl:
# Specify SYSTEMD unit
Journalctl-u MyApp
To view the live log:
Journalctl-f
Dependency relationships
Node.js applications often rely on other services, such as MongoDB, Redis, and so on. This means that MyApp may fail at power-on startup because these processes do not start. You can specify a dependency in a cell file, and SYSTEMD will start those dependencies first:
[Unit]
Description=myapp
Requires=mongodb.service Redis.service
After=mongodb.service Redis.service
Environment and user groups
SYSTEMD supports setting up user groups for each unit file, as well as environment variables. This facilitates the deployment and security of Node.js Web applications.
[Service]
environment=debug= ' myapp:* '
User=www
Group=http
Setting multiple environment variables allows you to write multiple environment= statements, such as:
environment=port=3000
Environment=host=localhost
Users and groups are more useful in production environments, and using specific users to run Node.js applications can largely limit the damage caused by cyber attacks.
Analyze System State
Output-Activated cells:
$ systemctl
The following command is equivalent:
$ systemctl List-units
The output failed to run the unit:
$ systemctl--failed
All available cell files are stored in the/usr/lib/systemd/system/and/etc/systemd/system/directories (the latter are higher priority). View all installed services:
$ systemctl List-unit-files
Working with cells
A unit configuration file can describe one of the following: System service (. Service), Mount Point (. Mount), sockets (. Sockets), System device (. device), swap partition (. swap), file path (. path), Start target (. target), timer (. timer) managed by SYSTEMD. See man 5 systemd.unit for details.
When using the Systemctl control unit, you typically need to use the full name of the cell file, including the extension (for example, Sshd.service). But some units can use shorthand in Systemctl.
If there is no extension, systemctl the extension as. Service. For example, Netcfg and Netcfg.service are equivalent.
The mount point is automatically converted to the appropriate. Mount unit. For example,/home is equivalent to Home.mount.
The device is automatically converted to the corresponding. Device unit, so the/dev/sda2 is equivalent to Dev-sda2.device.
Note: The names of some of the units contain a @ tag, (e.g. Name@string.service): This means that it is an instance of the template unit Name@.service. A string is called an instance identifier, which is passed as a parameter to the template unit when Systemctl calls the template unit, which replaces the%I in the template with this incoming parameter Indicator. Before instantiating, SYSTEMD checks the existence of the Name@string.suffix file (if it exists, it should be directly using the file instead of the template instantiation). In most cases, the shifting @ tag means that the file is a template. If a template unit is called without instantiating it, the call returns a failure because the%I in the template unit The indicator is not replaced.
Activate cells Now:
# Systemctl Start < unit >
Stop Unit Now:
# Systemctl Stop < unit >
Reboot unit:
# Systemctl Restart < unit >
Command Unit re-read configuration:
# Systemctl Reload < unit >
Output unit Running Status:
$ SYSTEMCTL Status < unit >
Check if the unit is configured to start automatically:
$ systemctl is-enabled < unit >
power-on Automatic activation Unit:
# Systemctl Enable < unit >
Note: If the service does not have install paragraphs, it generally means that they should be called automatically through other services. If you really need a manual installation, you can connect to the service directly, as follows (replace Foo with a real service name):
# ln-s/usr/lib/systemd/system/foo.service/etc/systemd/system/graphical.target.wants/
To cancel the Power-on automatic activation unit:
# systemctl Disable < unit >
The man page for the display unit (must be provided by the unit file):
# Systemctl Help < unit >
Reload the SYSTEMD, scanning for new or changed cells:
# Systemctl Daemon-reload
Power Management
Power management is not available until Polkit is installed.
If you are logged on to a local Systemd-logind user session and there is currently no other active session, the following command is not required to execute without root permission. Otherwise (for example, if another user is currently logged on to a TTY), SYSTEMD will automatically request the root password.
Reboot:
$ systemctl Reboot
To exit the system and stop the power supply:
$ systemctl Poweroff
Standby:
$ systemctl Suspend
Dormancy:
$ systemctl Hibernate
Mixed Hibernate mode (hibernate to hard drive and standby):
$ systemctl Hybrid-sleep
Writing Unit files
The syntax for the SYSTEMD unit file originates from the XDG Desktop Portal configuration file. Desktop file, originally from Microsoft Windows. ini file. The unit files can be loaded from two places, and the priority is from low to high, respectively:
/usr/lib/systemd/system/: Unit for package installation
/etc/systemd/system/: Unit installed by system administrator
Note: When SYSTEMD is running in user mode, the load path used is completely different.
The syntax of the unit file can refer to the unit that the system has installed, or to the examples chapter in the man Systemd.service.
Tip: notes that begin with # may also be used in unit-files, but only in new rows. Do not use the end of line comment after the systemd argument, otherwise the unit will fail to start.
Handling dependencies
When you use SYSTEMD, you can resolve its dependencies by correctly writing the unit configuration file. Typically, unit a requires unit B to run before a starts. In this case, add requires=b and after=b to the [unit] segment in the cell a configuration file. If this dependency is optional, you can add wants=b and after=b. Note that wants= and requires= do not imply after=, i.e. if the after= option is not established, these two units will be started in parallel.
Dependencies are usually used on services (service) instead of targets (target). For example, Network.target is typically introduced by a service that configures a network interface, so the custom unit is queued after the service because Network.target has started.
Type of service
When writing a custom service file, you can choose several different ways to start the service. The startup mode can be set through the type= parameter in the configuration file [Service] segment.
Type=simple (default): Systemd that the service will start immediately. The service process will not fork. If the service wants to start another service, do not use this type to start unless the service is a socket-activated type.
Type=forking:systemd that the service started successfully when the service process was fork and the parent process exited. For a regular daemon (daemon), use this type to start up unless you are certain that this startup method does not meet your requirements. Use this startup type to specify pidfile= at the same time in order to systemd the main process that can track the service.
Type=oneshot: This option applies to services that perform only one task and then exit immediately. You may need to set up Remainafterexit=yes so that SYSTEMD still considers the service active after the service process exits.
Type=notify: Same as type=simple, but the engagement service sends a signal to SYSTEMD when it is ready. The implementation of this notification is provided by libsystemd-daemon.so.
Type=dbus: If you start this way, systemd think the service is ready when the specified busname appears on the Dbus system bus.
TYPE=IDLE:SYSTEMD waits for all task (jobs) processing to complete before the idle type of cell is executed. In addition, other acts are similar to Type=simple.
More explanations for type can be referred to Systemd.service (5).
Modify an existing cell file
To change the unit files provided by the package, first create a directory named/etc/systemd/system/< cell name >.d/(such as/etc/systemd/system/httpd.service.d/), and then put the *.conf file Where you can add or reset parameters. The parameter precedence here is higher than the original cell file. For example, if you want to add an extra dependency, create a file that:
/etc/systemd/system/<unit>.d/customdependency.conf
[Unit]
requires=< New Dependency >
after=< New Dependency >
Other examples,
/etc/systemd/system/unit.d/customexec.conf
[Service]
execstartexecstart=
Execstart=new command
Want to know why you must empty the Execstart before you modify it
Here is an example of an automatic restart service:
/etc/systemd/system/unit.d/restart.conf
[Service]
Restart=always
Restartsec=30
Then run the following command to make the change take effect:
# Systemctl Daemon-reload
# Systemctl Restart < unit >
In addition, the same effect can be achieved by copying old unit files from/usr/lib/systemd/system/to/etc/systemd/system/and then modifying them. Cell files in the/etc/systemd/system/directory always have higher precedence than cell files of the same name in the/usr/lib/systemd/system/directory. Note that when a cell file in/usr/lib/is changed by a package upgrade, the custom cell files in/etc/are not synchronized with the update. In addition, you have to perform Systemctl reenable <unit>, and manually re-enable the unit. Therefore, it is recommended to use the previous method of using *.conf.
Tip: Use the Systemd-delta command to see which unit files are overwritten and which are modified. System maintenance requires a timely understanding of which units have been updated
Vim syntax highlighting support for cell configuration files
The VIM-SYSTEMD software package can be installed from the official warehouse to enable the unit configuration file to support syntax highlighting under VIM.
Goal (target)
The startup level (RunLevel) is an old concept. Now, SYSTEMD introduces a concept-goal (target) that is similar to the startup level functionality. Unlike the level of startup that is represented by numbers, each goal has a name and a unique function, and can enable multiple simultaneous. Some targets inherit services from other destinations and start new services. SYSTEMD provides a number of targets that mimic the sysvinit boot level and can still be switched using the old Telinit startup level command.
Get current target
Do not use the RunLevel command:
$ systemctl list-units--type=target
Create a new target
In Fedora, startup levels 0, 1, 3, 5, and 6 are given specific uses and correspond to a systemd target. However, there is no good way to migrate user-defined startup levels (2, 4). To achieve similar functionality, you can create a new target/etc/systemd/system/< new Target > (refer to/usr/lib/systemd/system/graphical.target) based on the original boot level, and create /etc/systemd/system/< the new target >.wants directory, and add a link to the additional service to it (point to the cell file in/usr/lib/systemd/system/).
Target table
SysV start level systemd target annotation
0 runlevel0.target, Poweroff.target interrupt system (Halt)
1, S, single runlevel1.target, rescue.target single-user mode
2, 4 runlevel2.target, Runlevel4.target, multi-user.target user-defined startup level, usually recognized as Level 3.
3 Runlevel3.target, Multi-user.target Multi-User, no graphical interface. Users can log on through a terminal or network.
5 Runlevel5.target, Graphical.target multi-user, graphical interface. Inherits the level 3 service and starts the graphical interface service.
6 Runlevel6.target, Reboot.target reboot.
Emergency Emergency.target emergency mode (emergency shell)
Toggle Start Level/target
SYSTEMD, the startup level is accessed through the target unit. Switch by using the following command:
# Systemctl Isolate Graphical.target
This command has no effect on the next boot. Equivalent to Telinit 3 or Telinit 5.
Modify default start level/target
The target of boot in is default.target, the default link to Graphical.target (roughly equivalent to the original boot level 5). You can change the default boot level through kernel parameters:
Tip: You can omit the extension. Target.
Systemd.unit=multi-user.target (roughly equivalent to level 3)
Systemd.unit=rescue.target (roughly equivalent to level 1)
Another method is to modify the Default.target. You can modify it by Systemctl:
# Systemctl Enable Multi-user.target
Command execution is displayed by Systemctl: The link/etc/systemd/system/default.target is created, pointing to the new default start level. This method is valid if and only if the target configuration file has the following content:
[Install]
Alias=default.target
At present, Multi-user.target, graphical.target all contain this paragraph content.
Temporary files
The files in/usr/lib/tmpfiles.d/and/etc/tmpfiles.d/describe how Systemd-tmpfiles creates, cleans, and deletes temporary files and directories, which are usually stored in/run and/tmp. The profile name is called/etc/tmpfiles.d/<program>.conf. The configuration here can overwrite a configuration with the same name in the/usr/lib/tmpfiles.d/directory.
Temporary files are usually provided with service files to generate the files and directories that the daemon needs. For example, the Samba service requires that the directory/run/samba exist and set the correct permission bits, just like this:
/usr/lib/tmpfiles.d/samba.conf
D/run/samba 0755 Root root
In addition, temporary files can be used to write certain content to specific files at power-on time. For example, to prevent the system from waking from a USB device, use the old/etc/rc.local to use echo usbe >/proc/acpi/wakeup, and now you can:
/etc/tmpfiles.d/disable-usb-wake.conf
W/proc/acpi/wakeup----USBE
See man 5 tmpfiles.d for details.
Note: This method cannot add parameters to the configuration file in/sys because Systemd-tmpfiles-setup is likely to run before the associated module loads. In this case, you need to first use the Modinfo < module name > to confirm the required parameters and set the parameters in a file under/ETC/MODPROBE.D. Alternatively, you can use the Udev rule to set the appropriate properties when the device is ready.
Timer
A timer is a configuration file with a. timer suffix, which records the actions triggered by time in the system, which replaces most of the functionality of Cron.
Log
SYSTEMD provides its own log system (logging system), called Journal. With the Systemd log, no additional setup log service (syslog) is required. Commands for reading logs:
# Journalctl
By default (when Storage= is set to auto in the file/etc/systemd/journald.conf), logging is written to/var/log/journal/. This directory is part of the SYSTEMD software package. If it is deleted, SYSTEMD does not automatically create it until the next time the package is upgraded, the directory is rebuilt. If the directory is missing, Systemd writes the log record to/run/systemd/journal. This means that the log will be lost after the system restarts.
Tip: If/var/log/journal/is located in the Btrfs file system, you should consider disabling write-time replication for this directory
Filter output
Journalctl can filter output based on specific fields, such as:
Show all logs after this startup:
# Journalctl-b
However, the general concern is not the log after the start, but the last boot (for example, just the system crashed). You can use the-B parameter:
Journalctl-b-0 Displays the information for this launch
Journalctl-b-1 Displays last-started information
Journalctl-b-2 Displays last-started information Journalctl-b-2
Show all messages from date (and optional time):
# journalctl--since= "2012-10-30 18:17:16"
Show all messages since minutes ago:
# journalctl--since "min ago"
Show the latest information
# journalctl-f
To display all messages for a particular program:
# JOURNALCTL/USR/LIB/SYSTEMD/SYSTEMD
To display all messages for a particular process:
# Journalctl _pid=1
Displays all messages for the specified cell:
# journalctl-u Netcfg
Show Kernel ring buffer:
# journalctl-k
Show Auth.log equivalent by filtering on Syslog facility:
# journalctl-f-L syslog_facility=10
For more information, see Man Journalctl, Man Systemd.journal-fields, and Lennert's blog post.
Log size limit
If you keep the log by the action above, the default log is limited to 10% of the filesystem capacity, that is, if the/var/log/journal is stored in a 50GiB root partition, the log stores up to 5GiB of data. You can modify the Systemmaxuse in/etc/systemd/journald.conf to specify the maximum limit. such as limit log max 50MiB:
systemmaxuse=50m
See Man journald.conf for details.
Use with Syslog
SYSTEMD provides socket/run/systemd/journal/syslog for compatibility with traditional logging services. All system information will be passed in. To make the legacy Log service work, you need to have the service link to the socket instead of the/dev/log (official description). The syslog-ng in the Arch software warehouse already contains the required configuration.
To set the boot boot syslog-ng:
# Systemctl Enable Syslog-ng
Here's a nice journalctl guide.
Forward Journald To/dev/tty12
In/etc/systemd/journald.conf enable the following:
Forwardtoconsole=yes
Ttypath=/dev/tty12
Maxlevelconsole=info
Reboot Journald:
# systemctl Restart Systemd-journald
Troubleshoot
Shutdown/reboot is slow
If the shutdown is particularly slow (or even the same as the crash), it is likely that a service that refuses to quit is at work. SYSTEMD will wait a while before trying to kill it. Read this article to make sure you are the victim of the problem.
Short-time Process no logging
If Journalctl-u Foounit.service does not show any output of a short process, try the PID instead. For example, if the Systemd-modules-load.service execution fails, then query its PID (for example, 123) with Systemctl status Systemd-modules-load, and then retrieve the PID-related log Journalctl-b _pid=123. Log metadata for Run-time processes (such as _systemd_unit and _comm) are collected in the/proc directory in random order. To fix the problem, you must modify the kernel so that it provides the data through a socket connection, similar to Scm_credentials.
Diagnosing startup problems
Use the following kernel parameters to boot: systemd.log_level=debug systemd.log_target=kmsg log_buf_len=1m
Prevent memory from being dumped when a program crashes
To use the old kernel dump, create the following file:
/etc/sysctl.d/49-coredump.conf
Kernel.core_pattern = Core
Kernel.core_uses_pid = 0
And then run:
#/usr/lib/systemd/systemd-sysctl
You may also need to perform the "unlimit" Setting File Size:
$ ulimit-c Unlimited