Article directory
-
- Why configure the program as a service?
- Version support
- Principle of self-starting service at boot
- Configuration steps
- Configuration item explanation
-
- Configure parent
- Configure subkeys
-
- `[Unit]` configuration subkey
-
- - `Description`: used to set the description information of the service.
- - `Requires`: used to specify other services on which the service depends.
- - `After`: used to specify the order in which services are started. You can set which services should be started after.
- - `Before`: used to specify the order in which services are started. You can set which services should be started before.
- `[Service]` configuration subkey
-
- - `ExecStart`: used to specify the startup command of the service.
- - `WorkingDirectory`: used to specify the working directory of the service.
- - `Environment`: used to set the environment variables of the service.
- - `User`: used to specify the user under which the service runs.
- - `Group`: used to specify the user group in which the service runs.
- `[Install]` configuration subkey
- systemd official documentation (systemd.service complete configuration options)
- vscode related plug-ins: Systemd Helper
- Link systemd configuration files using soft links
- systemd service configuration related instructions
-
- - `systemctl start <service>`: Start a service.
- - `systemctl stop <service>`: Stop a service.
- - `systemctl restart <service>`: Restart a service.
- - `systemctl reload <service>`: Reload the configuration file of a service to make it effective.
- - `systemctl enable <service>`: Set a service to be automatically enabled when the system starts.
- - `systemctl disable <service>`: Set a service not to be automatically enabled when the system starts.
- - `systemctl status <service>`: View the status of a service, including whether it is running, the last activity time and other information.
- - `systemctl is-active <service>`: Check whether a service is running.
- - `systemctl is-enabled <service>`: Checks whether a service has been set to be automatically enabled at system startup.
- - `systemctl list-units`: List all running units (including services, sockets, mount points, etc.).
- - `systemctl list-unit-files`: List all available unit files (including services, sockets, mount points, etc.).
- systemd other instructions
- systemd supports creating subdirectories in /etc/systemd/system so that we can easily manage our .service files (unsuccessful)
-
- Test 1: Create a subdirectory, create a soft link in the subdirectory, [execute systemctl daemon-reload], execute system enable xxx, error: Failed to enable unit: Unit file xxx.service does not exist.
- Test 2: Create a subdirectory, copy the .service file to the subdirectory, [execute systemctl daemon-reload], execute system enable xxx, error: Failed to enable unit: Unit file xxx.service does not exist.
- Test 3: Do not create a subdirectory, create a soft link to /etc/systemd/system, [execute systemctl daemon-reload], execute system enable xxx, success
- Configuration example
Why configure the program as a service?
When we start a program under a Linux system, we usually just use a command or execute a script. So, why do we need to configure the program as a service? What are the benefits of doing this?
1. Automatic start
After being configured as a service, the program will start automatically when the system starts, no manual operation is required. This ensures that the program can run automatically after the system is restarted, preventing the program from failing to start due to human negligence or other reasons.
2. Running in the background
After being configured as a service, the program will run as a background process and will not occupy the terminal or user session. This ensures that the program continues to run in the background, even if the user logs out or closes the terminal.
3. Scheduled restart
By configuring the service, you can set the service to automatically restart when it exits abnormally. This can improve the stability of the program and ensure that it can be restored in time when problems occur.
4. Simplify management
After being configured as a service, you can use system tools (such as systemctl
) to manage the service, such as starting, stopping, restarting, viewing status, etc. This makes it easy to manage and monitor the running status of the program.
5. Integrate systems
After being configured as a service, the program can be integrated with other services and components of the system. For example, you can set the dependencies of a service to ensure that the service is started before other services are started; you can also integrate the service with logging and monitoring systems to facilitate management and troubleshooting.
6. Automatic logging
After configuring it as a service, the system will automatically collect the log information of the service. It does not matter whether you are a C++ program, a Java program, a Python program, or a shell script. You can use the following command to view it:
journalctl -u 服务名 --no-pager
Version support
In different Ubuntu versions, the method of configuring the startup service may be different. The following are several common Ubuntu versions and the types of services they support on boot. This article mainly explains how Ubuntu 16.10 and higher versions use systemd
the service startup method as the init system.
1. Ubuntu 14.04 and earlier versions: Use upstart
as the default init system
You can create a .conf
file to configure the startup service and place it /etc/init/
in the directory.
/etc/rc.local
old version
rc.local
It is a way to configure a self-starting service in Ubuntu. It belongs to an early version of the init system. Specifically, rc.local
it is the method used in Ubuntu 14.04 and earlier versions, which is used upstart
as the default init system.
rc.local
is a script file located at /etc/rc.local
. In this file you can add commands or scripts to be executed when the system starts. These commands or scripts will be executed automatically when the system starts.
The following are rc.local
the steps to use the configuration to start the service automatically at boot:
-
Open
rc.local
the file:sudo nano /etc/rc.local
-
Add the command or script you want to execute in the file. For example, if you want to start a
my_service
service named , you can add the following:/path/to/your/service
Note that the command or script must be executable.
-
Save and close the file.
-
Make sure
rc.local
the file has executable permissions:sudo chmod +x /etc/rc.local
-
Restart the system and the service will be automatically executed when the system starts.
It should be noted that rc.local
this method is no longer recommended in newer Ubuntu versions because it is based on older upstart
systems. For systemd
newer versions of Ubuntu that use the init system, it is recommended to use systemd
the method to configure the startup service.
new version
In some newer Ubuntu versions, such as Ubuntu 16.04 and higher, rc.local
the file is disabled by default because these versions use systemd
the init system as the default. The contents of the file systemd
will not be executed automatically .rc.local
In order to use files in these versions rc.local
, this can be achieved through configuration rc-local.service
. rc-local.service
Is a service unit used to execute the contents of the file systemd
when the system starts .rc.local
Here are rc-local.service
the steps to configure:
-
Create
rc-local.service
file:sudo nano /etc/systemd/system/rc-local.service
-
Add the following content to the file:
[Unit] Description=/etc/rc.local Compatibility ConditionPathExists=/etc/rc.local [Service] ExecStart=/etc/rc.local start Type=forking TimeoutSec=0 RemainAfterExit=yes [Install] WantedBy=multi-user.target
-
Create
rc.local
file:sudo nano /etc/rc.local
-
rc.local
Add the command or script to be executed in the file . -
Save and close the file.
-
Set
rc.local
file permissions:sudo chmod +x /etc/rc.local
-
Enable
rc-local.service
:sudo systemctl enable rc-local.service
-
Start
rc-local.service
:sudo systemctl start rc-local.service
rc.local
The contents of the file will be automatically executed when the system starts.
For newer Ubuntu versions, the way you use rc.local
and rc-local.service
may not be best practice. The recommended systemd
method is to configure the auto-start service at boot so that it is consistent with the current init system.
2. Ubuntu 15.04 to 16.04 versions: used systemd
as the init system by default, but still compatibleupstart
You can use upstart
the method to configure the startup service, or use systemd
the method.
3. Ubuntu 16.10 and higher: used systemd
as the init system by default
You can use systemd
the method to configure the auto-start service at boot.
Summarize
systemd
It is the current mainstream init system, and most Ubuntu versions support its use systemd
to configure self-starting services at boot. However, for older versions of Ubuntu, you may need to upstart
configure the startup service.
Principle of self-starting service at boot
Take using systemd as the system initialization manager as an example. systemd is a Linux system and service manager, which is responsible for starting, stopping and managing various services in the system.
When the system starts, systemd will read /etc/systemd/system/
the service configuration file in the directory and start the corresponding service according to the instructions in the configuration file. Fields in the configuration file ExecStart
specify the command or script to be executed, and WorkingDirectory
fields specify the working directory of the command or script.
By using systemctl enable
the command, we tell systemd to link the service configuration file to the system's default target (default target), so that the service starts automatically when the system starts.
When the system starts, systemd will start the service according to the instructions in the configuration file. If the service starts successfully, systemd will mark the service's status as "active". If the service fails to start, systemd will mark the service's status as "failed".
By using systemctl start
the command we can start the service manually. The service can be stopped using systemctl stop
the command.
By using systemctl disable
the command, we can disable the service so that it does not start automatically when the system starts.
Summary: Use systemd to manage the starting and stopping of services. By configuring the service configuration file and linking it to the default target of the system, the service starts automatically when the system starts.
Configuration steps
Take systemd
the self-starting method as a service in the init system as an example. The following are the steps to configure the auto-start service at boot:
1. Create configuration file
Create a service configuration file .service
with a suffix such as my_service.service
.
2. Edit configuration file
Open the file with a text editor and add the following content:
[Unit]
Description=My Service
After=network.target
[Service]
ExecStart=/path/to/your/script.sh
WorkingDirectory=/path/to/your/working/directory
[Install]
WantedBy=default.target
In the above configuration, /path/to/your/script.sh
you need to replace it with the path of the script you want to run at boot and /path/to/your/working/directory
the working directory of the script.
3. Copy configuration files
Move the service configuration file to /etc/systemd/system/
the directory:
sudo mv my_service.service /etc/systemd/system/
4. Enable the service
Enable the service using the following command:
sudo systemctl enable my_service
5. Start the service
Start the service using the following command:
sudo systemctl start my_service
The service will now start automatically every time the computer is powered on.
6. Stop service
If you need to stop the service, you can use the following command:
sudo systemctl stop my_service
7. Disable services
If you need to disable the service, you can use the following command:
sudo systemctl disable my_service
Configuration item explanation
Configure parent
In systemd, configuration files usually have .service
an extension, and use INI格式
. A .service
file can contain the following three configuration items:
-
[Unit]
: This configuration item defines the basic properties of the service, such as service description, dependencies, startup sequence, etc. In this configuration item, you can set the name, description, dependencies, startup sequence, etc. of the service. -
[Service]
: This configuration item defines the specific execution method of the service, such as the service startup command, environment variables, working directory, etc. In this configuration item, you can set the service startup command, environment variables, working directory, etc. -
[Install]
: This configuration item defines the installation method of the service, such as the service startup level, startup sequence, etc. In this configuration item, you can set the startup level, startup sequence, etc. of the service.
These three configuration items respectively define the basic attributes, specific execution methods and installation methods of the service.
In addition to [Unit]
, [Service]
and [Install]
, systemd also supports some other configuration items for further defining and configuring services. The following are some commonly used configuration items:
-
[Path]
: Used to monitor changes in files or directories and trigger the start, stop or restart of services when changes occur. -
[Timer]
: Used to define a timer, which can trigger the start, stop or restart of the service at a specified time interval or a specific point in time. -
[Socket]
: Used to define a socket, which can listen to a specified network port or UNIX domain socket and trigger the start of the service when there is a connection request. -
[Mount]
: Used to define a mount point, which can trigger the start, stop or restart of the service when the specified file system is mounted or unmounted. -
[Automount]
: Used to define an automatic mount point, which can automatically mount the file system when the specified file system path is accessed. -
[Swap]
: Used to define the swap space, which can trigger the start, stop or restart of the service when the specified swap file or partition is enabled or disabled.
Configure subkeys
[Unit]
Configure subkeys
- Description
: Used to set the description information of the service.
- Requires
: Used to specify other services on which the service depends.
- After
: Used to specify the order in which services are started. You can set which services should be started after.
- Before
: Used to specify the order in which services are started. You can set which services should be started before.
[Service]
Configure subkeys
- ExecStart
: Used to specify the startup command of the service.
- WorkingDirectory
: used to specify the working directory of the service.
- Environment
: Used to set the environment variables of the service.
- User
: Used to specify the user under which the service runs.
- Group
: Used to specify the user group under which the service runs.
[Install]
Configure subkeys
- WantedBy
: Used to specify the target under which the service is started.
WantedBy
It is an option in the systemd service configuration file, used to specify the startup level (target) to which the service belongs. A startup level is a set of target units that define services to be started during system startup.
In systemd, the startup level is represented by the target unit. Each target unit is a collection of related service units, used to define which services should be started when the system starts at different stages. For example, multi-user.target
is a common startup level used to indicate that the system has booted into multi-user mode, and all services related to user interaction should be started at this time.
WantedBy
Options are used to specify the startup level to which the service belongs. It accepts the name of a target unit as an argument. When you place the service configuration file in /etc/systemd/system/
a directory and use systemctl enable
the command to enable the service, systemd will WantedBy
add the service to the corresponding startup level based on the target unit specified in the option.
In the above example, WantedBy=multi-user.target
it means that the service should belong to multi-user.target
the startup level, that is, the service should be started when the system has been started in multi-user mode.
In systemd, there are the following common startup levels (targets):
poweroff.target
: The target unit when the system is shut down.rescue.target
: The target unit for system rescue, providing a minimal set of functions for repairing system problems.multi-user.target
: Target unit for multi-user mode, used for normal multi-user operation.graphical.target
: The target unit of the graphical interface mode, used to start the graphical interface environment.reboot.target
: The target unit when the system restarts.
In addition to the above common startup levels, there are other specific startup levels, such as network.target
(target unit after network startup is completed), default.target
(default target unit, usually or multi-user.target
) graphical.target
, etc.
For ordinary programs, they are usually configured to belong to a startup level of multi-user.target
or graphical.target
so that they can start automatically when the system boots to multi-user mode or graphical interface mode. You can choose the appropriate startup level according to your needs.
- RequiredBy
: Used to specify which targets depend on the service.
systemd official documentation (systemd.service complete configuration options)
https://www.freedesktop.org/software/systemd/man/systemd.service.html
vscode related plug-ins: Systemd Helper
It is convenient for us to edit the systemd configuration file:
Link systemd configuration files using soft links
Files can be .service
created as soft links to actual files. Doing this keeps the service configuration file in its original location while /etc/systemd/system
creating a link under the directory so that systemd can find and manage the service.
step
Here are the steps to create a soft link:
- Create a soft link under
/etc/systemd/system
the directory to the actual file. For example, assuming the actual file is located/path/to/my-service/my-service.service
, you can create a soft link using the following command:
or:sudo ln -s /path/to/my-service/my-service.service /etc/systemd/system/
sudo ln -s /path/to/my-service/my-service.service /etc/systemd/system/my-service.service
Note: systemd requires that the soft link must be the same as the target name. If it is different, Failed to enable unit: File xxx.service: Link has been severed
an error will be reported when systemctl enable xxx is executed.
- Make sure the file permissions for soft links are set correctly. Generally speaking, the owner of a soft link should be
root
the user, and the permissions should be644
:sudo chown root:root /etc/systemd/system/my-service.service sudo chmod 644 /etc/systemd/system/my-service.service
This way the service configuration file will remain in its original location and the soft link will be under /etc/systemd/system
the directory, allowing systemd to find and manage the service. The advantage of this is that when the service configuration file needs to be modified or updated, it only needs to be done in the original location without modifying the soft link.
Note: If you configure it with a soft link, when you disable the service, the .service soft link under /etc/systemd/system will be deleted; but if it is a normal file, when you disable the service, the .service soft link under /etc/systemd/system will not be deleted. .service file deletion
Please see the test example below:
- Ordinary
.service
file mode (.service
copy the file/etc/systemd/system
below):
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up# systemctl enable ky_ai_algo_manager.service
Created symlink /etc/systemd/system/default.target.wants/ky_ai_algo_manager.service → /etc/systemd/system/ky_ai_algo_manager.service.
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up#
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up# systemctl disable ky_ai_algo_manager.service
Removed /etc/systemd/system/default.target.wants/ky_ai_algo_manager.service.
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up#
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up# ll /etc/systemd/system/ky_ai_algo_manager.service
-rwxr-xr-x 1 root root 240 Aug 16 11:36 /etc/systemd/system/ky_ai_algo_manager.service*
- Soft link method (
/etc/systemd/system
create a soft link in to link to the actual file):
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up# systemctl disable ky_ai_algo_manager
Removed /etc/systemd/system/ky_ai_algo_manager.service.
Removed /etc/systemd/system/default.target.wants/ky_ai_algo_manager.service.
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up#
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up#
root@nvidia:/userdata/testOnebuttonDeploy/shsany_ai/clean_up# ll /etc/systemd/system/ky_ai_algo_manager.service
ls: cannot access '/etc/systemd/system/ky_ai_algo_manager.service': No such file or directory
systemd service configuration related instructions
- systemctl start <service>
: Start a service.
- systemctl stop <service>
: Stop a service.
- systemctl restart <service>
: Restart a service.
- systemctl reload <service>
: Reload the configuration file of a service to make it effective.
- systemctl enable <service>
: Set a service to be automatically enabled when the system starts.
- systemctl disable <service>
: Set a service not to be automatically enabled when the system starts.
- systemctl status <service>
: Check the status of a service, including whether it is running, the last activity time and other information.
Note that when using systemctl status to check the status of a service, paging may occur because the service log information is too long, blocking program execution. In this case, you can add an --no-pager
option to suppress paging, such as:systemctl status $SERVICE_NAME --no-pager
- systemctl is-active <service>
: Check if a service is running.
- systemctl is-enabled <service>
: Checks whether a service has been set to be automatically enabled at system startup.
- systemctl list-units
: List all running units (including services, sockets, mount points, etc.).
- systemctl list-unit-files
: List all available unit files (including services, sockets, mount points, etc.).
systemd other instructions
View the systemd service log (journalctl -u $SERVICE_NAME --no-pager -u $LINE_COUNT)
To view the logs of a systemd service, you can use journalctl
the command. journalctl
The command is used to view systemd logs, including system logs and service logs.
To view the logs of a service, you can use the following command:
journalctl -u $SERVICE_NAME
Among them, $SERVICE_NAME
is the name of the service whose logs are to be viewed. This will display log entries related to the service.
Additional options are available to further filter and format the log. For example, you can use -n
options to specify the number of log entries to display, use -f
options to track logs in real time, use --since
the and --until
options to specify a time range, and so on.
Here are some example commands:
# 显示最近的10条服务日志
journalctl -u $SERVICE_NAME -n 10
# 实时跟踪服务日志
journalctl -u $SERVICE_NAME -f
# 显示指定时间范围内的服务日志
journalctl -u $SERVICE_NAME --since "2022-01-01" --until "2022-01-02"
systemd supports creating subdirectories in /etc/systemd/system so that we can easily manage our .service files (unsuccessful)
systemd will recursively traverse /etc/systemd/system
all files in the directory .service
and files in subdirectories .service
. This means that you can /etc/systemd/system
create subdirectories under the directory and place your service configuration files in the subdirectories.
For example, if you /etc/systemd/system
create a my-service
subdirectory named under a directory and my-service.service
place a service configuration file in that subdirectory, systemd will still be able to find and manage the service.
This mechanism of recursive traversal allows you to better organize and manage configuration files for multiple services without causing confusion.
Test 1: Create a subdirectory, create a soft link in the subdirectory, [execute systemctl daemon-reload], execute system enable xxx, error: Failed to enable unit: Unit file xxx.service does not exist.
[]
Optional, the same below
Test 2: Create a subdirectory, copy the .service file to the subdirectory, [execute systemctl daemon-reload], execute system enable xxx, error: Failed to enable unit: Unit file xxx.service does not exist.
Test 3: Do not create a subdirectory, create a soft link to /etc/systemd/system, [execute systemctl daemon-reload], execute system enable xxx, success
Could it be that I can only /etc/systemd/system
stay down ? Subdirectories not supported?
Configuration example
20230802
ky_ai_convert_video.service
[Unit]
Description=ky_ai_convert_video
After=network.target
[Service]
ExecStart=/ky/tml/ky_ai_convert_video/kyai_video_converter
WorkingDirectory=/ky/tml/ky_ai_convert_video
Restart=always
RestartSec=3
[Install]
WantedBy=default.target
test
Open a log monitoring:tail -f ky_ai_api.log
Kill process:
ps -ef | grep convert
kill <pid>
I found that it got up again after three seconds:
Restart testing:
The program runs normally