Ubuntu startup service systemd.service configuration tutorial (Ubuntu service) (Linux service) upstart

Article directory

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 systemdthe service startup method as the init system.

1. Ubuntu 14.04 and earlier versions: Use upstartas the default init system

You can create a .conffile to configure the startup service and place it /etc/init/in the directory.

/etc/rc.local

old version

rc.localIt is a way to configure a self-starting service in Ubuntu. It belongs to an early version of the init system. Specifically, rc.localit is the method used in Ubuntu 14.04 and earlier versions, which is used upstartas the default init system.

rc.localis 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.localthe steps to use the configuration to start the service automatically at boot:

  1. Open rc.localthe file:

    sudo nano /etc/rc.local
    
  2. Add the command or script you want to execute in the file. For example, if you want to start a my_serviceservice named , you can add the following:

    /path/to/your/service
    

    Note that the command or script must be executable.

  3. Save and close the file.

  4. Make sure rc.localthe file has executable permissions:

    sudo chmod +x /etc/rc.local
    
  5. Restart the system and the service will be automatically executed when the system starts.

It should be noted that rc.localthis method is no longer recommended in newer Ubuntu versions because it is based on older upstartsystems. For systemdnewer versions of Ubuntu that use the init system, it is recommended to use systemdthe method to configure the startup service.

new version

In some newer Ubuntu versions, such as Ubuntu 16.04 and higher, rc.localthe file is disabled by default because these versions use systemdthe init system as the default. The contents of the file systemdwill 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.serviceIs a service unit used to execute the contents of the file systemdwhen the system starts .rc.local

Here are rc-local.servicethe steps to configure:

  1. Create rc-local.servicefile:

    sudo nano /etc/systemd/system/rc-local.service
    
  2. 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
    
  3. Create rc.localfile:

    sudo nano /etc/rc.local
    
  4. rc.localAdd the command or script to be executed in the file .

  5. Save and close the file.

  6. Set rc.localfile permissions:

    sudo chmod +x /etc/rc.local
    
  7. Enable rc-local.service:

    sudo systemctl enable rc-local.service
    
  8. Start rc-local.service:

    sudo systemctl start rc-local.service
    

rc.localThe contents of the file will be automatically executed when the system starts.

For newer Ubuntu versions, the way you use rc.localand rc-local.servicemay not be best practice. The recommended systemdmethod 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 systemdas the init system by default, but still compatibleupstart

You can use upstartthe method to configure the startup service, or use systemdthe method.

3. Ubuntu 16.10 and higher: used systemdas the init system by default

You can use systemdthe method to configure the auto-start service at boot.

Summarize

systemdIt is the current mainstream init system, and most Ubuntu versions support its use systemdto configure self-starting services at boot. However, for older versions of Ubuntu, you may need to upstartconfigure 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 ExecStartspecify the command or script to be executed, and WorkingDirectoryfields specify the working directory of the command or script.

By using systemctl enablethe 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 startthe command we can start the service manually. The service can be stopped using systemctl stopthe command.

By using systemctl disablethe 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 systemdthe 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 .servicewith 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.shyou need to replace it with the path of the script you want to run at boot and /path/to/your/working/directorythe 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 .servicean extension, and use INI格式. A .servicefile can contain the following three configuration items:

  1. [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.

  2. [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.

  3. [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:

  1. [Path]: Used to monitor changes in files or directories and trigger the start, stop or restart of services when changes occur.

  2. [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.

  3. [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.

  4. [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.

  5. [Automount]: Used to define an automatic mount point, which can automatically mount the file system when the specified file system path is accessed.

  6. [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.

WantedByIt 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.targetis 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.

WantedByOptions 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 enablethe command to enable the service, systemd will WantedByadd the service to the corresponding startup level based on the target unit specified in the option.

In the above example, WantedBy=multi-user.targetit means that the service should belong to multi-user.targetthe 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):

  1. poweroff.target: The target unit when the system is shut down.
  2. rescue.target: The target unit for system rescue, providing a minimal set of functions for repairing system problems.
  3. multi-user.target: Target unit for multi-user mode, used for normal multi-user operation.
  4. graphical.target: The target unit of the graphical interface mode, used to start the graphical interface environment.
  5. 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.targetor graphical.targetso 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:

Insert image description here
Insert image description here

Link systemd configuration files using soft links

Files can be .servicecreated as soft links to actual files. Doing this keeps the service configuration file in its original location while /etc/systemd/systemcreating a link under the directory so that systemd can find and manage the service.

step

Here are the steps to create a soft link:

  1. Create a soft link under /etc/systemd/systemthe 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:
    sudo ln -s /path/to/my-service/my-service.service /etc/systemd/system/
    
    or:
    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 severedan error will be reported when systemctl enable xxx is executed.

  1. Make sure the file permissions for soft links are set correctly. Generally speaking, the owner of a soft link should be rootthe user, and the permissions should be 644:
    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/systemthe 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 .servicefile mode ( .servicecopy the file /etc/systemd/systembelow):
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/systemcreate 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-pageroption 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 journalctlthe command. journalctlThe 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_NAMEis 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 -noptions to specify the number of log entries to display, use -foptions to track logs in real time, use --sincethe and --untiloptions 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/systemall files in the directory .serviceand files in subdirectories .service. This means that you can /etc/systemd/systemcreate subdirectories under the directory and place your service configuration files in the subdirectories.

For example, if you /etc/systemd/systemcreate a my-servicesubdirectory named under a directory and my-service.serviceplace 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

Insert image description here

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.

Insert image description here

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/systemstay 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

Insert image description here

Kill process:

ps -ef | grep convert
kill <pid>

I found that it got up again after three seconds:

Insert image description here

Restart testing:

The program runs normally

Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/Dontla/article/details/132038293